teaLeef
teaLeef

Reputation: 1989

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?

Upvotes: 1

Views: 1009

Answers (2)

Pshemo
Pshemo

Reputation: 124275

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.

Upvotes: 3

J4v4
J4v4

Reputation: 810

Actually, no.

A method can be public, protected, private or package private. 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.

Upvotes: 2

Related Questions