javainheritancename-hiding

this refers to what when a non-overridden method is invoked on a subclass object?


Consider the following code:

class Person {
    String className = "Person";

    void printClassName () {
        System.out.println("I am " + this.className);
        System.out.println("I am " + this.getClass().getSimpleName());
    }
}

class Employee extends Person {
    // intentionally hiding this field
    String className = "Employee";
}

public class App {
    public static void main(String[] args) {
        Employee raghu = new Employee ();
        raghu.printClassName();
    }

}

I have a few questions.

  1. When an object of subclass is created, how many objects are actually created? Only one, extending the properties of superclass by introducing new properties defined in subclass? Or two, the subclass object that we have access to and a superclass object, whose existence is hidden from us?

  2. If two objects are created, which object is in charge when a non-overridden method is invoked on the subclass object? In other words, what does this refer to inside a non-overridden method? The hidden superclass object or the subclass object?

  3. If your answer for #2 is the hidden object of superclass, then why the code above prints "I am Employee" for System.out.println("I am " + getClass().getSimpleName()); inside printClassName.

  4. If your answer for #2 is the object of subclass, then why the first line inside printClassName prints "I am Person"?


Solution

  • You declare the variable as type Employee

    this.className
    

    refers to the className in that class.

    this.getClass().getSimpleName()
    

    this.getClass() returns the class Employee, since that's how you declared the variable, which is why the getSimpleName() returns "Employee"