无法从静态上下文中引用非静态 变量
1 class Point
2 {
3 int x,y;
4 Point()
5 {
6 this.x = 0;
7 this.y = 0;
8 }
9 Point(int xx, int yy)
10 {
11 this();
12 this.x = xx;
13 this.y = yy;
14 }
15 public void Print(){
16 System.out.println(this.x);
17 System.out.println(this.y);
18 }
19 }
20
21 public class Test{
22 Point pt = new Point();
23 Point pt1 = new Point(1,2);
24 public static void main(String[] args)
25 {
26 pt.Print();
27 pt1.Print();
28 }
29 }
30
2 {
3 int x,y;
4 Point()
5 {
6 this.x = 0;
7 this.y = 0;
8 }
9 Point(int xx, int yy)
10 {
11 this();
12 this.x = xx;
13 this.y = yy;
14 }
15 public void Print(){
16 System.out.println(this.x);
17 System.out.println(this.y);
18 }
19 }
20
21 public class Test{
22 Point pt = new Point();
23 Point pt1 = new Point(1,2);
24 public static void main(String[] args)
25 {
26 pt.Print();
27 pt1.Print();
28 }
29 }
30
以上代码会产生如下错误:
Test.java:26: 无法从静态上下文中引用非静态 变量 pt
pt.Print();
^
Test.java:27: 无法从静态上下文中引用非静态 变量 pt1
pt1.Print();
^
2 错误
问题解释:
在Test类中,main函数为静态,该函数中不能引用非静态的变量,对于pt,pt1两个对象定义为非静态的,所以出现以上错误;把对象定义为静态的即可;
1 static Point pt = new Point();
2 static Point pt1 = new Point(1,2);
2 static Point pt1 = new Point(1,2);
说明:类中静态成员(属性、方法)会优先于构造方法进行初始化
浙公网安备 33010602011771号