I am getting an error with this following code fragment
The error is : cannot reference x before supertype constructor has been called (and pointing out the statement at comment 1)
class Con{
int x =10;
Con(){
this(++x); //1
System.out.println("x :"+x);
}
Con(int i){
x=i++;
System.out.println("x :"+x);
}
}
In the main method I have this statement
Con c1=new Con();
I don't understand the error. Can someone explain what is actually happening here?
When creating an instance of a class, the constructor first calls it's super class constructor to initialize the super class fields. Once all the super class constructors have run, then only the current constructor continues to initialize it's own field.
Now, when you add a this()
call in your constructor, it doesn't call the super class constructor. This is because, the first statement in a constructor is either a chain to super class constructor - using super()
, or a different constructor of the same class - using this()
.
So, you can't pass the field in this()
, because the field is isn't initialized yet. But it doesn't really make sense, why you are trying to do something like that?
Remember, the compiler moves the field initialization code inside each constructor of your class. So, your constructor is effectively equivalent to:
Con() {
this(++x); //1
// This is where initialization is done. You can't access x before it.
x = 10;
System.out.println("x :"+x);
}
This is true even with super()
call. So, the below code will also give you the same error (considering Con
extends another class with a parameterized constructor):
Con() {
super(++x); //1
System.out.println("x :"+x);
}
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