使getVar方法最终化
这绝对是您需要做的。
如果要使用方法的功能来初始化对象,则不应让子类破坏该方法。
回答您的问题,防止出现此问题的 另 一种方法是
getVar在中将其设为私有
A。
查看此代码的简化版本:
// A.javaclass A { private final String var; public A(){ var = getVar(); var.length(); } private String getVar(){ return "This is the value"; }}class B extends A { private final String other; public B(){ other = "Other string"; } public String getVar(){ return other; }}class Main{ public static void main( String [] args ) { new B(); }}顺便说一句,为什么您将它们放置为静态嵌套类,只是造成混乱?



