NumericPrime
NumericPrime

Reputation: 73

Field values changed by super-constructor are reset? (Java)

I have a abstract class that implements the Runnable interface but doesn't provide an implementation of the run method. The constructor calls the run method.

Then I have a second abstract class that extends the first. The constructor of this class calls its superconstructor which calls the still unimplemented run method. This class also has a field "field" with the standard value 1.

Finally I use an anonymous inner class to implement this method and change the value of the field to 2. When using the object however the value of the field has been reset back to 1.

My code looks like this:

MainClass.java

package mainPackage;
public class MainClass {

    public MainClass() {
        ExtendingClass s=new ExtendingClass() {
            @Override
            public void run() {
                field=2;
                System.out.println(field);
            }
        };
        System.out.println(s.field);
    }

    public static void main(String[] args) {
        new MainClass();
    }

}

SuperClass.java

package mainPackage;

public abstract class SuperClass implements Runnable{
    public SuperClass() {
        run();
    }
}

ExtendingClass.java

package mainPackage;

public abstract class ExtendingClass extends SuperClass {
    int field=1;
    public ExtendingClass() {
        super();
    }

}

It seems that this problem only occurs when changing a field the superclass doesn't have the field being changed.

It also seems the reset occurs right after the superconstructor is done.

Upvotes: 1

Views: 67

Answers (1)

pL4Gu33
pL4Gu33

Reputation: 2085

For such a case you can use the debugger. There you see that the field=2 will be execute BEFORE (because of super constructor) the init(=1) of the field.

Upvotes: 1

Related Questions