静态成员

静态成员,共享内存,共用同一块内存区域。其值会被多个对象改变。

public class ob2 {
    int i=47;
    public void call() {
        System.out.println("调用call()方法");
        for(i=0;i<3;i++) {
            System.out.print(i+" ");
            if(i==2) {
                System.out.println("
");
            }
        }
    }
    public ob2() {//定义构造方法
    }
    public static void main(String[] args) {
        ob2 t1=new ob2();//创建对象t1
        ob2 t2=new ob2();//创建对象t2
        t2.i=60;
        System.out.println("对象t1调用i的结果:"+t1.i);//依然是47
        t1.call();
        System.out.println("对象t2调用i的结果:"+t2.i);
        t2.call();
    }
}

public class ob2 {
    static int i=47;//定义静态变量
    public void call() {
        System.out.println("调用call()方法");
        for(i=0;i<3;i++) {
            System.out.print(i+" ");
            if(i==2) {
                System.out.println("
");
            }
        }
    }
    public ob2() {//定义构造方法
    }
    public static void main(String[] args) {
        ob2 t1=new ob2();//创建对象t1
        ob2 t2=new ob2();//创建对象t2
        t2.i=60;//更改内存i的值
        System.out.println("对象t1调用i的结果:"+t1.i);
        t1.call();//循环结束,i的值被更改为3
        System.out.println("对象t2调用i的结果:"+t2.i);//输出3
        t2.call();//重新循环
    }
}

 

原文地址:https://www.cnblogs.com/xixixing/p/8182893.html