程序功能:通過兩個類 StaticDemo、LX4_1 說明靜態變量/方法與實例變量/方法的區別。
?
package Pack1;public class Try {public static void main(String[] args) {// TODO Auto-generated method stubSystem.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; 非靜態方法中可以訪問靜態數據成員xy=newY;//x=20; } }
?
?