日期:2014-05-20 浏览次数:20786 次
public class Test{ private static final Myclass object1; private static final Myclass object2=new Myclass(“2”); private final Myclass object3; static{ object4=new Myclass(“4”); } public Test(){ object5= new Myclass(“5”); } { object6=new Myclass(“6”); } public static void main(String args[]){ new Test(); } }
public class Test{ // private static final Myclass object1;编译不通过,必须赋初值,或者在静态语句块中赋值。 private static final Myclass object2=new Myclass("2"); private final Myclass object3;//这个finally不是很清楚 static{ object1 = new Myclass("1"); Myclass object4 = new Myclass("4");//要加Myclass } public Test(){ Myclass object3 = new Myclass("5");//要加Myclass } { object3 = new Myclass("3");//如果注掉这句,构造方法会报错。放在构造方法也可。 Myclass object6 = new Myclass("6");//要加Myclass } public static void main(String args[]){ new Test(); } } class Myclass{ Myclass(String i){ System.out.println(i); } }
------解决方案--------------------
class Myclass{
Myclass(int i){
System.out.println(i);
}
}
public class Test{
//private static final Myclass object1;//这行必须给出初始值 因为有final否则编译失败
private static final Myclass object2=new Myclass(2);
//private final Myclass object3;//同上
static{
Myclass object4=new Myclass(4);
}
public Test(){
Myclass object5= new Myclass(5);
}
{
Myclass object6=new Myclass(6);
}
public static void main(String args[]){
new Test();
}
}
如果把那两条注释掉则输出为2 4 6 5