This concept had similarities to methods but not the same as the method. These constructors are used to instantiate the object created for that class. If the program already had used the defined constructor, the compiler will use it. If there is not constructor mentioned in the code compiler will add the default constructor. The constructor name should be the same as the class name.
Types of constructor
- Default Constructor
- No Argument Constructor
- Parameterized Constructor
1. Default Constructor
If there is no implementation made on the constructor of the class is made it is known as the default constructor. In this scenario, While creating an object for that class, the compiler will create a default constructor to instantiate the variables.
In this scenario, there is no implementation made on the constructor. So, the Compiler will create a new default constructor.
2. No Argument Constructor
In this concept, some user-defined implementation is made in the constructor and while creating the object, it will call the implemented constructor.
Sample Program
----------------------------------------------------------------------------------------------------------------------
package oops;
public class StudentName {
StudentName(){
System.out.println("Argument Constructor");
}
public static void main(String[] args) {
StudentName student = new StudentName();
}
}
----------------------------------------------------------------------------------------------------------------------
Output:
Argument Constructor
3. Parameterized Constructor
In this type, Parameters are passed into the constructor at the time of object creation. In the below example we had one parameterized constructor and parameters are passed during object creation.
Sample Program
----------------------------------------------------------------------------------------------------------------------
package oops;
public class StudentName {
StudentName(String name){
System.out.println("Student name is : " + name);
}
public static void main(String[] args) {
StudentName student = new StudentName("Ram");
}
}
----------------------------------------------------------------------------------------------------------------------
Output:
Student name is : Ram
Consider I have implemented parameterized constructor in my code and I called no argument constructor during object creation. In this scenario, a compile-time error will occur. Have a look at the below screenshot.
Comments
Post a Comment