In Java, the constructor is a block of codes similar to the method. The constructor is called when the instance of the object is created. The constructor is a special method which is used to initialize the object.
- The constructor doesn’t have any return type.
- The constructor name must be same as the class name.
There are two types of Constructors In java.
- Default Constructor – When a constructor doesn’t have any parameter then it is called default parameter. If there is no constructor in the class then the compiler automatically creates a default constructor.
- Parameterized constructor – If a constructor has a specific number of parameters then it is called the parameterized constructor.
class DConst { DConst() { System.out.println("Default Constructor called"); } public static void main(String args[]) { DConst d1=new DConst(); } } Output: Default Constructor called
Program to print the default values of the default constructor –
class Student { int rno; String name; void display() { System.out.println(rno+" "+name); } public static void main(String args[]) { Student s1=new Student(); Student s2=new Student(); s1.display(); s2.display(); } } Output: 0 null 0 null
- Program For Parameterized Constructor –
class Student { int rno; String name; Student(int i,String n) { rno = i; name = n; } void display() { System.out.println(rno+" "+name); } public static void main(String args[]) { Student s1 = new Student(101,"Tanmay"); Student s2 = new Student(102,"Shivam"); s1.display(); s2.display(); } } Output: 101 Tanmay 102 Shivam
Constructor Overloading:
If the constructor with the same name but different in the number of parameters in a class is called constructor overloading.
class Student { int rno; String name; int age; Student(int i,String n) { rno = i; name = n; } Student(int i,String n,int a) { rno = i; name = n; age=a; } void display() { System.out.println(rno+" "+name+" "+age);} public static void main(String args[]){ Student s1 = new Student(100,"Tanmay"); Student s2 = new Student(101,"Shivam",17); s1.display(); s2.display(); } } Output: 100 Tanmay 0 101 Shivam 17