non-static variable this cannot be referenced from a static context
来源:互联网 发布:java中拼接字符串方法 编辑:程序博客网 时间:2024/05/16 04:45
今天练习java的时候,发现一个有意思的问题,实际上这个问题对于计算机专业的学生来说可能是个常识。但是不知有多有像我一样半路出家的朋友,甚或是计算机相关专业的朋友注意到这个问题了。
闲言少叙,言归正传,先看代码。
错误代码一:
class ConsDemo { private static String name; //declare name attribute private static int age; // delcare age attribute public static void tell(){ System.out.println("name: "+this.name+",age: "+this.age); } }
上面这段代码会报错,错误如题。
原因何在呢?
先调整代码如下:
class ConsDemo { private String name; //declare name attribute private int age; // delcare age attribute public void tell(){ System.out.println("name: "+this.name+",age: "+this.age); } }
上面的代码则可以运行,又或可以改写成这样:
修正代码二:
class ConsDemo { private static String name; //declare name attribute private static int age; // delcare age attribute public static void tell(){ System.out.println("name: "+name+",age: "+age); }}
至此可以看出结论来了:
如果错误代码一中去掉this指针,则错误会变成:non-static variable name cannot be referenced from a static context non-static variable age cannot be referenced from a static context;其意为:上下文环境中找不到静态变量name,age;
因此下面的修正代码一中去掉了tell方法的static 声明,而修正代码二中则是为name,age属性添加了静态声明关键字。
故得出的结论是:
静态方法里只能使用静态变量;
同样的:
类方法里,只能使用类变量。
- non-static variable this cannot be referenced from a static context
- Java - Why non-static variable cannot be referenced from a static context?
- Non-static method cannot be referenced from a static context
- Cannot use this in a static context
- Cannot use this in a static context
- Cannot use this in a static context
- Cannot use this in a static context
- Cannot use this in a static context
- Cannot make a static reference to the non-static method setInAnimation(Animation) from the type View
- Cannot make a static reference to the non-static method getLocalActivityManager() from the type Acti
- android Toast报错 Activity context.this cannot be resolved to a variable
- android Toast报错 Activity context.this cannot be resolved to a variable
- android Toast报错 Activity context.this cannot be resolved to a variable
- Cannot make a static reference to the non-static method
- Cannot make a static reference to the non-static method
- Cannot make a static reference to the non-static field
- Cannot make a static reference to the non-static method
- Cannot make a static reference to the non-static field
- hibernate抓取策略fetch / batch-size
- PHP处理Oracle的CLOB
- 求一个数的n次方 power
- gcc编译器的spec规范
- linux下邮件查看命令
- non-static variable this cannot be referenced from a static context
- arm指令介绍
- 重写Repeater,使其支持空模版(列表为空时显示) 后遇到的问题
- 看了一次又一次,每次都有不同的感受....
- 通过代码创建UILable,并设置平移旋转字体颜色等属性
- HDU 1517 A Multiplication Game
- c中几个copy函数的使用细节
- 国外编程网站
- linux连接器ld