访问对象的属性和行为

1、对象调用成员

public class TransferProperty {
    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 TransferProperty() {}
    
    public static void main(String[] args) {
        TransferProperty t1 = new TransferProperty();
        TransferProperty t2 = new TransferProperty();
        t2.i = 60;
        System.out.println("第一个实例对象t1调用变量i的结果:" + t1.i++);
        t1.call();
        System.out.println("第二个实例对象t2调用变量i的结果:" + t2.i);
        t2.call();
    }
}

运行结果:

第一个实例对象t1调用变量i的结果:47
调用call()方法
0 1 2 
第二个实例对象t2调用变量i的结果:
60 调用call()方法 0 1 2

说明:   

  main()方法中首先实例化一个对象,然后调用类的成员变量和方法。但是在运行结果中可以看到,虽然使用两个对象调用同一个成员变量,结果却不同。因为在打印这个成员变量的值之前将该值重新赋值为60,但在赋值时使用的时第二个对象t2调用成员变量,所以在第一个对象t1调用成员变量打印该值时仍然时成员变量的初始值。由此可见,两个变量的产生是互相独立的,改变类t2的i的值,不会影响到t1的i的值。

2、对象调用静态成员变量

public class TransferProperty {
    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 TransferProperty() {}
    
    public static void main(String[] args) {
        TransferProperty t1 = new TransferProperty();
        TransferProperty t2 = new TransferProperty();
        t2.i = 60;
        System.out.println("第一个实例对象t1调用变量i的结果:" + t1.i++);
        t1.call();
        System.out.println("第二个实例对象t2调用变量i的结果:" + t2.i);
        t2.call();
    }
}

运行结果:

第一个实例对象t1调用变量i的结果:60
调用call()方法
0 1 2 

第二个实例对象t2调用变量i的结果:3
调用call()方法
0 1 2 

 说明:

  从运行结果可以看到,由于使用t2.i=60语句改变类静态成员变量的值,使用对象t1调用成员变量的值也是60,这正是i值被定义为静态成员变量的效果,即使使用两个对象对同一个静态成员变量进行操作,依然可以改变静态成员变量的值,因为在内存中两个对象同时指向同一块内存区域。t1.i++语句指向完毕后,i值变为3.当再次调用call()方法时又被重新赋值为0,做循环打印操作。

原文地址:https://www.cnblogs.com/sunzhongyu008/p/11284331.html