tra*_*veh 9 java effective-java
从Effective Java第2版,第17项:
对于每个公共或受保护的方法或构造函数,文档必须指出方法或构造函数调用哪些可覆盖的方法
后来在同一个项目中说:
构造函数不得直接或间接调用可覆盖的方法.
这两个陈述不矛盾,还是我错过了什么?
在构造过程中调用可重写的方法是允许的——这没有什么违法的。
不建议在构造期间调用可重写的方法- 通常不建议在构造期间调用可重写的方法,因为这可能会导致暴露不完整的对象并限制系统的可预测性。
public class A {
final int a;
public A() {
a = method();
}
protected int method() {
return 42;
}
@Override
public String toString() {
return "A{" + "a=" + a + '}';
}
}
public class B extends A {
@Override
protected int method() {
System.out.println("this=" + this);
return 96;
}
}
public void test() {
System.out.println("B = " + new B());
}
Run Code Online (Sandbox Code Playgroud)
请注意,您的第一个引用仅指文档,而不是代码。我建议唯一的问题是使用“ must”, “ should”可能更合适。