源代码【有错误】 class StaticDemo { static int x; int y; static{ x=10; } public static int getX() { return x; } public static void setX(int newX) { x = newX; } public int getY() { return y; } public void setY(int newY) { y = newY; } public static void main(String[] args) { System.out.println("静态变量x="+StaticDemo.getX()); System.out.println("实例变量y="+StaticDemo.getY()); 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()); } }
更改后
class StaticDemo {
static int x;
int y;
static {
x = 10;
}
public static int getX() {
return x;
}
public static void setX(int newX) {
x = newX;
}
public int getY() {
return y;
}
public void setY(int newY) {
y = newY;
}
public static void main(String[] args) {
System.out.println("静态变量x=" + StaticDemo.getX());
// System.out.println("实例变量y="+StaticDemo.getY());
//getY不是static修饰的不能这样获取
StaticDemo a = new StaticDemo();
System.out.println("实例变量y=" + a.getY());// 要用实例调用
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());
}
}
总结:
static 修饰的属性可以跨类调用;
static修饰的方法可以直接通过类来调用,不需要将之实例化;