程序功能:通过两个类 StaticDemo、LX4_1 说明静态变量/方法与实例变量/方法的区别。
package Pack1; public class Try { public static void main(String[] args) { // TODO Auto-generated method stub 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; public static int getX(){ return x;//静态方法中可以访问静态数据成员x } public static void setX(int newX){ x=newX; } public int getY(){//int前加static试试(静态方法中不可以访问非静态数据成员y) return y; } public void setY(int newY){//试试增加 x=20; 非静态方法中可以访问静态数据成员x y=newY; //x=20; } }