方法不会覆盖 Eclipse 中的包可见方法
从 Eclipse Java 编译器设置:方法不会覆盖包可见方法
“包默认方法在不同的包中不可见,因此不能被覆盖。启用此选项时,编译器将发出信号这种情况要么是错误,要么是警告。”
如何触发此警告/错误?我正在寻找代码示例。
From the Eclipse Java compiler setting: Method does not override package visible method
"A package default method is not visible in a different package, and thus cannot be overridden. When this option is enabled, the compiler will signal such scenario either as an error or a warning."
How can I trigger this Warning/Error? I'm looking for a code example.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Foo.java:Bar.java
:
应该这样做。
来自 Eclipse 帮助文档:
Foo.java:
Bar.java:
Should do it.
From the Eclipse Help docs:
和
And
为什么这个警告或错误很重要,请考虑以下示例:
将整个内容复制粘贴到 Eclipse 中,它将整理类和包。然后运行
Main
类。您可能期望它打印,但它却打印
这是令人困惑的行为,意外地破坏了多态性。它这样做的原因是
Animal
子类Cat
和Dog
实际上根本没有重写方法makeNoise
,因此,当在Animal
上调用makeNoise
时,它会使用Animal
实现。要修复此代码,请将
public
或protected
修饰符添加到Animal
makeNoise
方法,然后重新运行现在的代码按预期工作。在这个简单的示例中,很清楚发生了什么,但在更复杂的情况下,这种行为可能会非常令人困惑,并且可能是不正确的,因此应该认真对待该警告。An example of why this warning or error is important consider the following example:
Copy paste the whole thing into Eclipse and it will sort out the classes and packages. Then run the
Main
class. You might expect it to printBut instead it prints
This is confusing behaviour which unexpectedly breaks polymorphism. The reason it does this is the
Animal
subclassesCat
andDog
have not actually overridden the methodmakeNoise
at all, so whenmakeNoise
is called on anAnimal
it uses theAnimal
implementation.To fix this code add
public
orprotected
modifiers to theAnimal
makeNoise
method, then rerun the code it will now work as expected. In this simple example its quite clear what is going on, but in a more complicated situation this behaviour could be extremely confusing and probably incorrect so the warning should be taken seriously.