class TiXing{ float up,height; static float down; TiXing(float x,float y,float z){ up=x; height=y; down=z; } } public class ep3_9{ public static void main(String args[]){ TiXing one=new TiXing(1,2,3); System.out.println("one's down is:"+one.down); TiXing two=new TiXing(4,5,6); System.out.println("one's down is:"+one.down); System.out.println("two's down is:"+two.down); System.out.println("TiXing's down is:"+TiXing.down); } }
實例方法和類方法對實例變量和類變量的訪問
實例方法可以對當前對象的實例變量進行操作,也可以對類變量進行操作。實例方法由實例對象調用。
類方法不能訪問實例變量,只能訪問類變量。類方法由類名或者實例對象調用。類方法中不能出現this或者super關鍵字
class TiXing{ private float up,height; private static float down; TiXing(float x,float y,float z){ up=x; height=y; down=z; } public void display(){ System.out.println("up is:"+up+"height is:"+height+"down is:"+down); } public static void change(float number){ down=number; //System.out.println("height:"+height);//出錯 } } public class ep3_9{ public static void main(String args[]){ TiXing one=new TiXing(1,2,3); one.display(); TiXing two=new TiXing(4,5,6); one.display(); two.display(); //TiXing.display();//出錯 one.change(101); one.display(); two.change(102); two.display(); } }