简体   繁体   中英

Overriding methods from different classes in java

From a java tutorial

  • A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final.

  • A subclass in a different package can only override the non-final methods declared public or protected.

What is the difference though?If a method is not declared private then it must be public or protected no?

This points can be rephrased as: you can override only method to which your class have access to, and if this method is not final .

So if you are creating class outside of package in which base class (or interface) is placed you can override only non-final public and protected methods.

If derived class is in same package as base class then you can also override non-final methods without access modifier (package-protected).

You can never override private methods.

Actually, no.

A method can be public, protected, private or . The method is package private if you don't specify an access modifier.

It's obvious why a class from a different package cannot overwrite package private members.

The difference is the default (or package-private ) access modifier. If you don't specify an access modifier, then only other classes in the same package can access it, regardless of whether they are subclasses or not.

For more information: http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM