Frage

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?

War es hilfreich?

Lösung

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);
}

Andere Tipps

Con(){
    this(++x); //1
    System.out.println("x :"+x);
}

At this very moment, Con does not yet exist. It first instantiates by calling the other constructor. That means that x does not exist yet (it is created as soon as the other constructor instantiates). So you can't reference it yet.

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

private static int x = 10;

First call inside a constructor can only be this() or super() , if their is none of them then compiler automatically insert a call to super but in your constructor you called other constructor by using this() . basically whenever you construct an object the superclass is first initialized then the subclass's members gets initialized.So you can not refer to uninitialized members as they gets initialized after superclass's members and superclass itself.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top