• Post Reply Bookmark Topic Watch Topic
  • New Topic

access specifier for an overriding method can allow more, but not less, access than the overridden  RSS feed

 
saidi Bandi
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

HI,

When I am reading the java documentationwebpage, I came across below.

Modifiers

"The access specifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the superclass can be made public, but not private, in the subclass".

my question is, on which basis java given the above statement. I need some more information on this.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm going to explain this with an example. Suppose you have a class:

Note that the method is public. This means that it can be called from any other class.

Now, suppose we create a subclass, which overrides the method, but makes it protected (this is not allowed, I'll explain why).

The method in Subclass is protected, which means it can only be called from subclasses or classes in the same package as Subclass.

But you can assign an instance of Subclass to a variable of type Superclass:

Since someMethod() is public in Superclass, this would mean that suddenly from other classes (outside the package) you could call Subclass.someMethod(). That should not be possible, since someMethod() is protected in Subclass.

So, allowing this would create a hole in the access control mechanism.
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Find out about the Liskov Substitution Principle (=LSP). That says that whenever you carry out an action on a superclass object, you can carry out the same action on a subclass object without surprises. If the superclass' method is feasible because it is accessible, the subclass method must be feasible because it is accessible.
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another thing the LSP means, is that your subclass method must be feasible because it does not throw any “new” exceptions. The javac tool catches new checked Exceptions but that does not mean you may throw new unchecked Exceptions.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!