我想了解各种情况下类实例的初始化。
在 JLS-7 第 12.5 节中,没有提到如何以及何时初始化最终实例变量?如果实例变量声明为最终变量,我可以参考一点来理解行为吗?
public class Test {
public static void main(String args[]){
Child c1 = new Child();
}
}
class Parent{
final int a =30;
Parent(){
System.out.println("From super Contsrutor "+a);
meth();
}
void meth(){
System.out.println("From super");
}
}
class Child extends Parent{
final int e=super.a;
int b=30;
void meth(){
System.out.println("From Sub e=" +e+", b="+b);
}
}
给出如下输出
From super Contsrutor 30
From Sub e=0,b=0
然而
public class Test {
public static void main(String args[]){
Child c1 = new Child();
}
}
class Parent{
final int a =30;
Parent(){
System.out.println("From super Contsrutor "+a);
meth();
}
void meth(){
System.out.println("From super");
}
}
class Child extends Parent{
final int e=a;
void meth(){
System.out.println("From Sub " +e);
}
}
将输出作为
From super Contsrutor 30
From Sub 30