Java-Constructor

Constructor

Java provides a special construct named constructor exclusively for creating an object of a and initializing its instance variables. Constructor look like methods but aren’t. The constructor  has the same name as the class and has no return type specified. Once defined, the constructor is automatically called immediately after the object is created, before the new operator completes. We cannot invoke a constructor on an existing object.

Program

31

Program Source

class Data{
    
    Data()
    {
        System.out.println("I am called automatically");
    }
    
    void call()
    {
        System.out.println("I am called manually");
    }
}

public class Javaapp {

    public static void main(String[] args) {
       
        Data d1  = new Data();
        d1.call();
    }
}

Leave a Comment