The variable is null in a super call

I am using Java 7 and got 3 classes:

TestSuper.java

public abstract class TestSuper {
    public TestSuper() {
            testMethod();
    }

    protected abstract void testMethod();
}

TestNull.java

public class TestNull extends TestSuper {
    private String test = "Test";

    public TestNull() {
            super();
            System.out.println(test);
    }

    @Override
    protected void testMethod() {
            System.out.println(test);
    }

}

TestMain.java

public class TestMain {
    public static void main(String[] args) {
            new TestNull();
    }
}

Conclusion:

null
Test

Why is this happening and does it have a good workaround?

+4
source share
3 answers

When you call new TestNull();, you call the constructor of the class TestNull, which it calls the constructor super(): it contains a call to the method implemented in TestNullwhere you print the String field, at that time the subclass fields TestNullare not yet initialized, i.e. are null.

, , , () .

, .

? , : , - (.. TestSuper).

+6
+2

overridable ( private String test = "Test";) . , . , :

public TestSuper() {
       testMethod();
}

: ?

+1

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


All Articles