class Num{
private int i=0;
public void add(){i++;System.out.println("i="+i);}
public Num(){}
}
class Ber{
private Num n;
public Ber(Num n){
this.n=n;
this.n.add();
}
}
public class Test {
Num n=new Num();
public static void main(String[] args){
for(int i=0;i<3;i++){
Ber b=new Ber(n);
}
}
}
红色那行出现错误:non-static variable n cannot be referenced from a static context
找不到原因啊,哪位大神帮帮忙!!!
------解决方案--------------------
静态方法中不能调用非静态成员或方法,jvm加载顺序,静态优先。
修改为:
class Num{
private int i=0;
public void add(){i++;System.out.println("i="+i);}
public Num(){}
}
class Ber{
private Num n;
public Ber(Num n){
this.n=n;
this.n.add();
}
}
public class Test {
public static void main(String[] args){
Num n=new Num();
for(int i=0;i<3;i++){
Ber b=new Ber(n);
}
}
}