面向对象编程难点

public class ArgumentPassingTest {

    public static void main(String[] args) {
        int a = 1, b = 2;
        swap(a,b);
        System.out.println("a is " + a + " b is " + b);
        
        MyNumber obj1 = new MyNumber();
        MyNumber obj2 = new MyNumber();
        obj2.num = 10;//obj1 5, obj2 10
        swap(obj1, obj2);//swap obj1 and obj2
        //obj1 01, obj2 5
        System.out.println("obj1 is " + obj1.num + " obj2 is " + obj2.num);
    }
    
    public static void swap(int m, int n) {
        int s = m;
        m = n;
        n = s;
    }

    public static void swap(MyNumber obj3, MyNumber obj4) {
        int s = obj3.num;
        obj3.num = obj4.num;
        obj4.num = s;
    }
}

按照C++语言的概念,里面的第二行执行结果应该是

a is 2 b is 1
但输出的结果却是a is 1 b is 2
令人大失所望!!!!!!
而第八行代码执行完了则可以按照一般思维得到”正确“的结果。
这是因为在C/C++中,obj称为指针,在Java中称为Reference
对象的赋值是Reference赋值,而基本类型是直接值考贝。

猜你喜欢

转载自www.cnblogs.com/gurilla/p/10305312.html