Why conclusion inheritance is unexpected

class Parent { private void method1() { System.out.println("Parent method1()"); } public void method2() { System.out.println("Parent method2()"); method1(); } } class Child extends Parent { public void method1() { System.out.println("Child method1()"); } public static void main(String args[]) { Child p = new Child(); p.method2(); } } 

ans

 Parent method2() Parent method1() 

If I create an object of class Child, then why does the output have a method of the parent class? even method1 is private in the parent. This shakes my concept of inheritance.

+7
source share
3 answers

It will call the child method if it overrides the parent method. But this is not so, since the parent method is private and therefore cannot be overridden.

When you intend to override a method from the parent class or interface, you should always annotate the method with @Override . If you did this, in this case you would get an error from the compiler, since child method1 does not override any method.

When the parent class is compiled, the compiler searches for method1 in the parent class. He finds it and sees that he is private. Since it is confidential, it knows that it is not overridden by any subclass, and thus statically links the method call to the private method it finds.

If method1 was protected or publicly accessible, the compiler will find this method and will know that this method can be overridden by a subclass. Therefore, it will not be statically bound to the method. Instead, it generates a bytecode that method1 will look for in a particular class at runtime, and then you get the expected behavior.

Think about it: if a subclass can override a private method, this method will no longer be closed.

+13
source

by default, the child class will have access to the parent method. you call p.method2 () ... which does not exist in the Child class, so it runs from the parent ...

Although method1 () is private, it is the parent .. it receives a call from a local method, that is, method2 () ... therefore method1 () got accessibility in method2 () ....

+2
source

Private members are not inherited by child classes. Therefore, you simply define a completely independent public void method1 in the subclass. Naturally, he is not involved in dynamic dispatch.

+1
source

All Articles