Disallow subclasses from overriding Java method

南笙酒味 提交于 2019-11-28 09:36:58

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

Simply make the method final.

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.

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