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
What is a constructor? Why do you need a constructor?
If the constructor is automatically generated by the compiler, why do you need to define your own constructor?
Describe the importance of parameterised constructors.
If a class is named DemoClass, what names are allowed as constructor names in the class DemoClass?