0
votes

i have been going through Inheritance in java. My question is if private members are not inherited how come they end up in memory. Is there something going on internally to resolve this issue or they are just hidden/un accesible wihout public member function of the parent class.

here is java doc "A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.

A nested class has access to all the private members of its enclosing class—both fields and methods. Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private members of the superclass."

2

2 Answers

2
votes

They are in memory, but you don't have access to them.

Example:

class A
{
    private int foo;

    public int getFoo( ) { return foo; }

    ...
}

class B extends A
{
   ...
}

Every instance of class B does, in fact, contain an integer foo under the hood.

But, you cannot access it directly, because it is declared private. You can access it indirectly, via the getFoo method, because that one is public.

2
votes

Your object has Class reference in it. Your object's Class had parent Class reference in it. That's why private methods are still in memory - they're referenced by parent class.

They are just inaccessible normally, you can access them with e.g. Method.setAccessible(). You can get Method's by reflection on parent Class.