禁止子类覆盖 Java 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13021472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Disallow subclasses from overriding Java method
提问by John
Suppose I have a method in a Java class, and I don't want any subclass of that class to be able to override that method. Can I do that?
假设我在 Java 类中有一个方法,并且我不希望该类的任何子类能够覆盖该方法。我可以这样做吗?
回答by yotommy
You can declare the method to be final
, as in:
您可以将方法声明为final
,如下所示:
public final String getId() {
...
}
For more info, see http://docs.oracle.com/javase/tutorial/java/IandI/final.html
有关详细信息,请参阅http://docs.oracle.com/javase/tutorial/java/IandI/final.html
回答by s.s.o
Simply make the method final.
只需将方法设为 final 即可。
回答by Mik378
If your method is not part of your builded API and isn't directly called by subclasses, prefer simply making your method private
.
如果你的方法不是你构建的 API 的一部分,也不是由子类直接调用,那么更喜欢简单地制作你的方法private
。
If your class hierarchy is contained in a single package, make your method in package scope (without keyword of scoping). Thus, only outside world (included your other own packages) can't access it and therefore can't override it.
如果您的类层次结构包含在单个包中,请在包范围内创建您的方法(没有范围关键字)。因此,只有外部世界(包括您自己的其他包)无法访问它,因此无法覆盖它。
If your method isn't really part of your API but has to be visible by subclasses even external, prefer make it protected
and final
如果您的方法实际上不是 API 的一部分,但必须对子类甚至外部可见,则更喜欢 make it protected
andfinal
Finally if your method is part of your API, make it public
and final
.
最后,如果您的方法是 API 的一部分,请将它public
和final
.