Change the access modifier of an overridden method in Java?

mre picture mre · Feb 17, 2012 · Viewed 23k times · Source

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.

Answer

Alex D picture Alex D · Feb 17, 2012

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.