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
.