Constructor in Java


☞Constructor is a special type of method that is used to initialize the object.

☞It is invoked at the time of object creation.

☞It constructs the values i.e. provides data for the instance variables of the object.


Rules to Create a Constructor

☞Constructor name must be same as its class name.

☞Constructor must have no explicit return type.

Example

class Example{
    
    Example(){
        System.out.println("I am Constructor");
    }
    
    void Example(){
        System.out.println("I am Function");
    }
    
    public static void main(String args[]){
        Example obj = new Example(); //implicitly constructor will be called
        obj.Example(); //explicitly calling a function
    }
    
}

Output

I am Constructor
I am Function