Turning a Method into Java Inheritance

package P1; public class Base { private void pri( ) { System.out.println("Base.pri()"); } void pac( ) { System.out.println("Base.pac()"); } protected void pro( ) { System.out.println("Base.pro()"); } public void pub( ) { System.out.println("Base.pub()"); } public final void show( ) { pri(); pac(); pro(); pub(); } } 

and

 package P2; import P1.Base; public class Concrete1 extends Base { public void pri( ) { System.out.println("Concrete1.pri()"); } public void pac( ) { System.out.println("Concrete1.pac()"); } public void pro( ) { System.out.println("Concrete1.pro()"); } public void pub( ) { System.out.println("Concrete1.pub()"); } } 

And I do

 Concrete1 c1 = new Concrete1(); c1.show( ); 

Now the output is displayed

Base.pri ()
Base.pac ()
Concrete1.pro ()
Concrete1.pub ()

Can someone explain why this is so? From what I understood about inheritance, this should have happened:

1) P2.concrete1 inherits P1.Base
2) An object c1 of a specific object is created
3) c1.show() . Since P1.Base.show () is public , it can be called.
4) Now in P2.concrete1, after inheritance, only native methods (pri, pac, pro, pub) and inherited methods P1.Base (pro, pub, show) are available.

Now WHY does it show Base.pri () and Base.pac () in the output when they are not even available?

It is clear that I do not have a clear fundamental understanding of inheritance. Can anyone explain this situation and how inheritance is really “structured”. I used to think that inherited methods and fields of a superclass simply overlap a subclass. But this line of reasoning is obviously wrong.

Thanks!

+7
source share
2 answers

The short answer is that you can override only visible methods. The first two methods pri and pac are private and protected packages, respectively. Since nothing outside the class can see the private method, it cannot be overridden. Similarly, since Concrete1 is in another package from Base , it cannot see Base.pac , so it cannot override it.

This means that while you define the pri and pac method in Concrete1 , these are just methods that have the same name as the methods in Base , rather than overriding. The other two methods, pro and pub are secure and public, so Concrete1 visible. As a result, the pro and pub methods in Concrete1 are method overrides with the same name in Base .

Since show defined in Base , he compiled a call to 4 methods, as defined in Base . When the JVM is executed, it searches to make sure that they are overridden, and if they execute the overridden methods. As explained above, pri and pac not redefined, so Base versions are executed, where Concrete1 versions are run as pro and pub .

If you moved the show method to Concrete1 instead of Base , then it would execute 4 methods, as defined in Concrete1 , since these would be the methods visible to show .

+11
source

Private and non-modifying design methods are not visible to its subclass. See here for more details.

0
source

All Articles