我想了解一个我在处理匿名课程时遇到的奇怪行为.
我有一个类在其构造函数中调用受保护的方法(我知道,设计很差,但这是另一个故事...)
public class A {
public A() {
init();
}
protected void init() {}
}
Run Code Online (Sandbox Code Playgroud)
然后我有另一个扩展A和覆盖的类init().
public class B extends A {
int value;
public B(int i) {
value = i;
}
protected void init() {
System.out.println("value="+value);
}
}
Run Code Online (Sandbox Code Playgroud)
如果我编码
B b = new B(10);
Run Code Online (Sandbox Code Playgroud)
我明白了
> value=0
Run Code Online (Sandbox Code Playgroud)
这是预期的,因为超级类的构造函数在Bctor 之前调用然后value仍然是.
但是在使用像这样的匿名类时
class C {
public static void main (String[] args) {
final int avalue = Integer.parsetInt(args[0]);
A a = new A() …Run Code Online (Sandbox Code Playgroud)