Change the access modifier of an overridden method in Java?

后端 未结 5 1637
-上瘾入骨i
-上瘾入骨i 2020-12-28 15:32

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

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

And

5条回答
  •  隐瞒了意图╮
    2020-12-28 16:25

    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.

提交回复
热议问题