Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the access modifier of an overridden method in Java?

Tags:

Is there a reason one can change the access modifier of an overridden method? For instance,

abstract class Foo{     void start(){...} } 

And then change the package-private access modifier to public,

final class Bar extends Foo{     @Override     public void start(){...} } 

I'm just asking this question out of curiosity.

like image 216
mre Avatar asked Feb 17 '12 14:02

mre


People also ask

Can we change the scope of the overridden method?

Yes, we can change the scope of the overridden method in the subclass.

When you use method overriding Can you change the access level of the method from protected to public why?

Being a public method any external class can call it. Access level of the overriding method doesn't affect visibility of the original method. After override, with any access levels, the original method can only be accessed by calling super in the subclass.

Can we change access modifier?

In C#, we can not change access modifier while overriding a method from base class. e.g. This is not valid in C#, It will give compile time error.


2 Answers

Java doesn't let you make the access modifier more restrictive, because that would violate the rule that a subclass instance should be useable in place of a superclass instance. But when it comes to making the access less restrictive... well, perhaps the superclass was written by a different person, and they didn't anticipate the way you want to use their class.

The programs people write and the situations which arise when programming are so varied, that it's better for language designers not to "second-guess" what programmers might want to do with their language. If there is no good reason why a programmer should not be able to make access specifiers less restrictive in a subclass (for example), then it's better to leave that decision to the programmer. They know the specifics of their individual situation, but the language designer does not. So I think this was a good call by the designers of Java.

like image 183
Alex D Avatar answered Oct 11 '22 16:10

Alex D


There is only one, you might want the override to be visible by more classes, since no modifier is default, public broadens that.

like image 22
Oscar Gomez Avatar answered Oct 11 '22 16:10

Oscar Gomez