为什么我写java程序时,明明一点语法错误都没有,但是编译时总会出这个错误:non-static variable this cannot be referenced from a static context?
害得我要在每一个变量、函数、类前加上static才能解决,为什么会这样呢?有没有什么好的解决方法?
...全文
39809打赏收藏
菜鸟求救!(non-static variable this cannot be referenced from a static context)
为什么我写java程序时,明明一点语法错误都没有,但是编译时总会出这个错误:non-static variable this cannot be referenced from a static context? 害得我要在每一个变量、函数、类前加上static才能解决,为什么会这样呢?有没有什么好的解决方法?
public class Test {
public String name;
public static void main(String[] args) {
name = "lskdjf"'//error
}
}
这是典型的错误,因为main方法是static的,不属于Test类,如果在他内部调用name,而name是每一个Test实例都有的变量,那main中应该去哪一个实例的name呢?所以你必须:
public static void main(String[] args) {
Test test = new Test();
test.name = "safsd";
}