Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private methods in Inheritance

Here's an interesting code snippet:

public class Superclass {

    public static void main (String[] args){
        Superclass obj = new Subclass();
        obj.doSomething(); #prints "from Superclass"
    }

    private void doSomething(){System.out.println("from Superclass");}
}

class Subclass extends Superclass {

    private void doSomething(){System.out.println("from Subclass");}

}

I know that subclasses do not inherit the private members of its parent, but here obj manages to call a method to which it should have no access. At compile time obj is of type Superclass, at runtime of type Subclass.

This probably has something to do with the fact that the call to doSomething() is taking place inside the driver class, which happens to be its own class (and why it's possible to invoke doSomething() in the first place).

So the question boils down to, how does obj have access to a private member of its parent?

like image 537
Victor Cheung Avatar asked Jan 18 '13 03:01

Victor Cheung


People also ask

Can we use private method in inheritance?

private methods are not inherited. A does not have a public say() method therefore this program should not compile.

What is private inheritance in Java?

Members of a class that are declared private are not inherited by subclasses of that class. Only members of a class that are declared protected or public are inherited by subclasses declared in a package other than the one in which the class is declared.

Can you access private variables in inheritance?

But, if you inherit a class that has private fields, including all other members of the class the private variables are also inherited and available for the subclass. But, you cannot access them directly, if you do so a compile-time error will be generated.

Are private methods inherited C++?

A derived class doesn't inherit access to private data members. However, it does inherit a full parent object, which contains any private members which that class declares.


2 Answers

You answered it yourself. As the private methods are not inherited, a superclass reference calls its own private method.

like image 42
Swapnil Avatar answered Oct 19 '22 16:10

Swapnil


Private methods are only for the owner.

Not even for the kids, relatives or friends of the owner.

like image 111
Alex Kreutznaer Avatar answered Oct 19 '22 17:10

Alex Kreutznaer