更改 Java 中重写方法的访问修饰符?
是否有理由可以更改重写方法的访问修饰符?例如,
abstract class Foo{
void start(){...}
}
然后将 package-private 访问修饰符更改为 public
,
final class Bar extends Foo{
@Override
public void start(){...}
}
我只是出于好奇才问这个问题。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Java 不允许您使访问修饰符变得更加严格,因为这会违反子类实例应可用于代替超类实例的规则。但是,当涉及到使访问更少限制时......好吧,也许超类是由不同的人编写的,并且他们没有预料到您想要使用他们的类的方式。
人们编写的程序以及编程时出现的情况千差万别,因此语言设计者最好不要“事后猜测”程序员可能想用他们的语言做什么。如果没有充分的理由说明程序员不能能够在子类中减少访问说明符的限制(例如),那么最好将这个决定留给程序员。他们知道自己的具体情况,但语言设计者却不知道。所以我认为这是 Java 设计者的一个很好的决定。
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.
扩展一个类意味着子类至少应该为其他类提供相同的功能。
如果他延长这一点,那么这不是问题。
扩展可以是添加新方法,也可以是向更多类提供现有方法,例如公开包访问方法。
Extending a class means the subclass should at least offer the same functionality to the other classes.
If he extends that, then it is not a problem.
Extending could be be either adding new methods or by offering existing methods to more classes like making a package-access method public.
只有一个,您可能希望覆盖对更多类可见,因为没有默认修饰符,public 扩大了这一点。
There is only one, you might want the override to be visible by more classes, since no modifier is default, public broadens that.
编辑:好的,我更改了答案来解决问题。
如果无法做到这一点,那么在某些情况下,类将无法实现 iterface 并扩展类因为它们具有相同的方法和不同的访问修饰符。
Edit: OK, I changed my answer to fix the problem.
If that couldn't be done, then there would be some cases where a class wouldn't be able to implement an iterface and extend a class because they have the same method with different access modifiers.