Another interview question about inheritance

topic description

public class Base {

private String baseName = "base";

public Base() {
    callName();
}

public void callName() {
    System.out.println(baseName);
}

static class Sub extends Base {
    private String baseName = "sub";

    public void callName() {
        System.out.println(baseName);
    }
}

public static void main(String[] args) {
    Base b = new Sub();
}

}

what result do you expect? What is the error message actually seen?

Why output: null?

Dec.17,2021

public class Base {

private String baseName = "base";//1

public Base() {
    callName();//2
}

public void callName() {
    System.out.println(baseName);
}

static class Sub extends Base {
    private String baseName = "sub";

    public void callName() {
        System.out.println(baseName);//3
    }
}

public static void main(String[] args) {
    Base b = new Sub();
}
}

Base b = new Sub (); initializes the parent class first, in the order like 1dint 2 new Sub (); 3 above. When entering the callName method, the properties of the subclass have not yet initialized the execution code, so what is printed is null.

.
Menu