Constructor
- Special method to initialize the object
- When object of the class is created, constructor is called
- Can be used to set initial value of attribute in object
- Constructor is public
- But in java we can create public, private, protected constructor
- Private constructor : within a class
Example:
public class ConstructorDemo {
int x;
private ConstructorDemo()
{
x=20;
}
public static void main (String[] args){
ConstructorDemo obj = new ConstructorDemo();
System.out.println(“x: “+obj.x);
}
}
Next Example:
public class ConstructorDemo {
int x; // Class attribute is created
// class constructor for the ConstructorDemo class is created
public ConstructorDemo() {
x = 5; // Initialization of value for the class attribute x
}
public static void main(String[] args) {
ConstructorDemo Obj = new ConstructorDemo(); //object of class ConstructorDemo is created which calls the constructor
System.out.println(Obj.x); // Print the value of x as output
}
}
Types:
- Default Constructor
- No argument constructor
- Parameterized Constructor