静态方法中只允许访问静态数据,那么,如何在静态方法中访问类的实例成员(即没有附加static关键字的字段或方法)?
 

package com;

class StaticDemo {
static int x;//静态变量x
int y;//实例变量y
static public int getX() {
return x;
}
static public void setX(int newX) {
x = newX;
}
public int getY() {

return y;
}
public void setY(int newY) {
y = newY;
}
}

public class ShowDemo {
public static void main(String[] args) {
System.out.println("静态变量x="+StaticDemo.getX());
//System.out.println("实例变量y="+StaticDemo.getY());// 非法,编译时将出错
//why
StaticDemo a= new StaticDemo();
StaticDemo b= new StaticDemo();
a.setX(1);
a.setY(2);
b.setX(3);
b.setY(4);
System.out.println("静态变量a.x="+a.getX());
System.out.println("实例变量a.y="+a.getY());
System.out.println("静态变量b.x="+b.getX());
System.out.println("实例变量b.y="+b.getY());
}
}