1.

When is the constructor of a class invoked?

Answer»

The constructor of a class is invoked at the time of object creation. Each time an object is created USING the new keyword, the constructor gets invoked. The constructor initializes the data members of the same class.

class Example {  Example() // constructor  {   } } Example obj=new Example(); // invokes above constructor

A constructor is used to initialize the state of the object. It contains a LIST of statements that are EXECUTED at the time of creation of an object.

For example,

public class Example {    Example()  // constructor of class Example    {        System.out.println("This is a constructor");    }    public static void main(String []args)    {        Example e=new Example();        // constructor Example() is invoked by creation of new object e            } }

The OUTPUT of the above is as follows:

$javac Example.java $java Example This is a constructor


Discussion

No Comment Found