Java学习笔记——实例变量,类变量的区别和应用,本文案例:获得一个梯形的上底下底和高

package te11128;

//本节知识点:实例变量,类变量

class Lader{
    double trapezoidalTop,trapezoidalHeight;    //实例变量
    static double trapezoidalBottom;  //类变量
    void setTop (double a) {
        trapezoidalTop =a;
    }
    void setBottom (double b) {
        trapezoidalBottom = b;
    }
    double getTop() {
        return trapezoidalTop;
    }
    double getBottom() {
        return trapezoidalBottom;
    }
}

public class Page78 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
//该程序从主类main方法开始执行,执行到Lader.trapezoidalBottom=100;java虚拟机首先将Lader
//的字节码加载到内存,同时为类变量"trapezoidalBottom"分配了内存坤见,并赋值100.
        
        Lader.trapezoidalBottom=100;  //Lader的字节码被加载到内存,通过类名操作类变量
        
//当执行Lader laderOne = new Lader();Lader laderTwo = new Lader();时,实例变量
//trapezoidalTop和trapezoidalHeight都两次分配内存空间,分别被对象laderOne和laderTwo
//引用,而类变量"trapezoidalBottom"不在分配内存,直接被对象laderOne和laderTwo引用、共享
        
        Lader laderOne = new Lader();
        Lader laderTwo = new Lader();
        laderOne.setTop(28);
        laderTwo.setTop(66);
        System.out.println("laderOne的上底:"+laderOne.getTop());
        System.out.println("laderOne的下底:"+laderOne.getBottom());
        System.out.println("laderTwo的上底:"+laderTwo.getTop());
        System.out.println("laderTwo的下底:"+laderTwo.getBottom());
    }
}


//类似乎破坏了封装性,实际上不是,当对象调用实例方法时,改革方法中出现的类变量也是该对象的变量,
//只不过这个变量和所有的其他对象共享而已。
 

猜你喜欢

转载自blog.csdn.net/YENTERTAINR/article/details/84695262