靜態只能調用靜態
非靜態: 對象名.方法名
package ti; //通過兩個類 StaticDemo、LX4_1 說明靜態變量/方法與實例變量/方法的區別。 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;// 非靜態方法中可以訪問非靜態數據成員y } public void setY(int newY) {//試試增加 x=20; 非靜態方法中可以訪問靜態數據成員x y = newY; } } public class t2 { 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(8); 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()); } }
打印結果:
靜態變量 x=0
靜態變量 a.x=3
實例變量 a.y=8
靜態變量 b.x=3
實例變量 b.y=4