An interview question about inheritance

topic description

class Super{
    private  String name = "Super";
    public String getName() {
        return this.name;
    }
}
public class Sub extends Super{
    private String name = "Sub";
    public static void main(String[] args) {
        Sub sub = new Sub();
        //Super
        System.out.println(sub.getName());
    }
}


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

I thought I would output sub, but I actually output super. I always thought that this refers to the caller of the method, getName () is called by sub, so the this should be sub, then the sub.name should be sub;, but this is obviously wrong

Dec.17,2021

The

subclass does not override the getName method, so the called getName method is the parent class. In the method of the parent class, this.name points to the address of the name attribute of the parent class.

if the subclass overrides the getName method of the parent class, the this.name of the subclass is sub.

Overloading in

Java is only for methods. First of all, getName is not overloaded. The call is the getName, of the Super class and the this, in this method points to the instance property of the Super.this.name class.


this points to the created Sub sub = new Sub ();. Object, Sub inherits Super and has two name attributes, one is its own name= "Sub", and the other is the parent class's name= "Super". Sub does not override the getName method, but calls the parent class's getName method, and this.name inherits the parent class's name= "super" attribute.

Menu