我有两个类,父类和子类,代码如下:
public class Parent {
public String word;
}
父类只包含一个公共字段。
public class Child extends Parent {
//super.word = "Simple field assignment.";
{
System.out.println(word);
}
String word2 = super.word = "Field assignment.";
{
System.out.println(word);
super.word = "Initialization block.";
System.out.println(word);
}
public Child(){
super.word="Constructor.";
System.out.println(word);
}
}
我想问的问题是为什么不允许简单的赋值'super.word = "word"',但是下面的双重赋值是可以的。有人可以具体说明后者到底发生了什么吗?
另外为什么初始化块内允许赋值?
如果我运行以下主程序:
public class FieldTest {
public static void main (String[] args)
{
Child c = new Child();
System.out.println("1: "+c.word);
System.out.println("2: "+c.word2);
}
}
结果是:
null
Field assignment.
Initialization block.
Constructor.
1: Constructor.
2: Field assignment.