KnowledgeBoat Logo
|

Computer Applications

Explain the statement, "you cannot invoke constructors as normal method calls".

Java Constructors

6 Likes

Answer

A constructor cannot be explicitly invoked like a method. It is automatically invoked via the new operator at the time of object creation. On the other hand, a method can be called directly by an object that has already been created. Normal method calls are specified by the programmer.

The below program highlights the difference in the way the constructor is invoked versus a normal method call:

class Test  {
    int a, b;
    public Test(int x, int y)   {
        a = x;
        b = y;
    }
    void add()  {
        System.out.println(a + b);
    }
}

class invokeConst   {
    public static void main(String args[])  {
        Test obj1 = new Test(10, 20);   // constructor invoked
        obj1.add();    // calling add() method
    }
}

Answered By

3 Likes


Related Questions