Constructor in java is a special method that is responsible for initializing the object.
Rules to create Java Constructor :
Basically there are differences between method and constructor.
- Name of the constructor should be same as the class name.
- Constructor should not have explicit return type.
- A constructor will be called implicitly when the new instance of object is created.
Types of Java Constructors :
1.Default constructor
2.Parameterized constructor
1.Java Default constructor : A constructor with no parameters or arguments are known as Default constructor in Java.
syntax of Default constructor :
1 2 3 4 |
className() { } |
Example of Default Constructor :
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class student { student() { System.out.println("student constrcutor is called"); } public static void main(String args[]) { Student s = new Student(); } } |
OUTPUT :
Zero Constructor Example In Java
- Java Parameterized constructor : A Constructor which contains parameters is known as Parameterized constructor.
syntax of Parameterized constructor :
1 2 3 4 |
className(arg1,arg2….) { } |
Example of parameterized Constructor :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
class student { int marks; String Grade; student(int m,String G) { System.out.println("student parameterized constrcutor is called"); marks=m; Grade=g; } void display() { System.out.println("The students marks is : "+marks); System.out.println("The students Grade is : "+Grade); } public static void main(String args[]) { Student s1 = new Student(80,"Grade A"); s1.display(); } } |
OUTPUT :
Parameterized Constructor Example In Java
Points to Remember :
- If we donot create an constructor, Java compiler takes the responsibility of creating an default constructor.