Disallow subclasses from overriding Java method

浪尽此生 提交于 2019-12-17 19:18:06

问题


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?


回答1:


You can declare the method to be final, as in:

public final String getId() {
   ...
}

For more info, see http://docs.oracle.com/javase/tutorial/java/IandI/final.html




回答2:


Simply make the method final.




回答3:


If your method is not part of your builded API and isn't directly called by subclasses, prefer simply making your method 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

Finally if your method is part of your API, make it public and final.



来源:https://stackoverflow.com/questions/13021472/disallow-subclasses-from-overriding-java-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!