首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

non-static variable n cannot be referenced from a static context,该如何解决

2013-04-21 
non-static variable n cannot be referenced from a static contextclass Num{private int i0public vo

non-static variable n cannot be referenced from a static context
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);
        }
    }
}

热点排行