Constructor overloading in java

I get an error with this piece of code

Error: cannot refer to x before the supertype constructor was called (and the operator is indicated in 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 operator

  Con c1=new Con(); 

I do not understand the error. Can someone explain what is really going on here?

+4
source share
3 answers

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); } 
+5
source
 Con(){ this(++x); //1 System.out.println("x :"+x); } 

At this very moment, Con does not exist yet. First, an instance is created by calling another constructor. This means that x does not exist yet (it is created as soon as an instance of another constructor is created). That way, you cannot reference it yet.

If you really need to reference it, you should use a static variable

 private static int x = 10; 
+2
source

The first call inside the constructor can be only this() or super() , if none of them exist, then the compiler automatically inserts the super call, but you call another constructor in your constructor using this (). basically, when you build an object that is first initialized by the superclass, then the members of the subclass are initialized. Thus, you cannot refer to uninitialized members, because they are initialized after the members of the superclass and the superclass itself.

0
source

Source: https://habr.com/ru/post/1496404/


All Articles