When creating an instance of a class, the constructor first calls the superclass of the class to initialize the fields of the superclass. When all the superclass constructors are started, only the current constructor continues to initialize its own field.
Now, when you add the call to this() to your constructor, it does not call the constructor of the superclass. This is because the first statement in the constructor is either a chain for the superclassical constructor — using super() , or another constructor of the same class — using this() .
So, you cannot pass the field to this() , because the field is not yet initialized. But it really doesn't make sense, why are you trying to do something like this?
Remember that the compiler moves the field initialization code inside each constructor of your class. So your constructor is effectively equivalent:
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 when super() called. Thus, the code below will also give you the same error (given that Con extends another class with a parameterized constructor):
Con() { super(++x); //1 System.out.println("x :"+x); }
source share