I do not understand why the below code displays the error Constructor call must be the first statement in a constructor
if I shift this(1);
to the last line in the constructor.
package learn.basic.corejava;
public class A {
int x,y;
A()
{
// this(1);// ->> works fine if written here
System.out.println("1");
this(1); //Error: Constructor call must be the first statement in a constructor
}
A(int a)
{
System.out.println("2");
}
public static void main(String[] args) {
A obj1=new A(2);
}
}
I've checked many answers on this topic on StackOverflow but I still could not understand the reason for this. Please help me to make clear about this error with some easy example and explanation.
As you know, this works:
A() {
this(1);
System.out.println("1");
}
Why? because it's a rule of the language, present in the Java Language Specification: a call to another constructor in the same class (the this(...)
part) or to a constructor in the super class (using super(...)
) must go in the first line. It's a way to ensure that the parent's state is initialized before initializing the current object.
For more information, take a look at this post, it explains in detail the situation.
The error tells you the problem
A()
{
System.out.println("1");
this(1); //Error: Constructor call must be the first statement in a constructor
}
i.e. you must call the constructor first
A()
{
this(1);
System.out.println("1");
}
this also applies to calls to super
class B extends A
{
B()
{
super();
System.out.println("1");
}
}
the reason being is answered here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With