Question

There are two class below:

public class Animal {
    private String name;
    public Animal(String name) {
         this.name = name;
    }
    public String getName() {
         return name;
    }
}

public class Cat extends Animal {
    public Cat(String name) {
         super(name);
    }
    public static void main(String[] args) {
         Cat cat = new Cat("Tom");
         System.out.println(cat.getName());
    }
}

The result is "Tom".

But the value is the property value of Animal or Cat? If is Animal, why cat can get it?

Was it helpful?

Solution

The property name although declared private in Animal is still inherited in Cat. But, we don't have direct access to it i.e. you can't use name with the . operator like cat.name = "Jerry". But, since the method getName is declared in Animal and thus has access to the private members of Animal. Also getName is public, so we can access it in Cat.

This means that we are accessing the private members of a super-class in a sub-class. This is pretty obvious. You may seem confused about it because many

How the name is set to Tom: - The name is set through the public constructor of Animal. And the constructor of Cat passes the value of name to the Animal constructor, which then sets it.

EDIT: When you say Cat cat = new Cat("Tom");, it means you have created only one object. An object of Cat. You haven't created an object of Animal. Although the constructor of Animal is called, it doesn't creates an instance of Animal. Int the above case, the property name belongs to the instance of Cat and not Animal.

OTHER TIPS

Animal has a private member name; as the constructor of Cat calls the constructor of Animal which stores the name, getName of Animal can return it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top