Java参数传递方式

Everything in Java are passed-by value.

基本类型的传递方式

基本类型是值传递,传递的是值得copy, 对于方法内的任何改变,都不会反映到原始的变量中。

对象的传递方式

对象传递的是对象的内存地址
一个小例子,仔细体会下,就明白了:

public class Test {
    class Dog {
        private int age;

        public Dog(int age) {
            this.age = age;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "Dog [age=" + age + "]";
        }

    }

    private Dog dog = new Dog(0);

    public void chageAge(Dog dog) {
        dog.setAge(100);
        Dog dog2 = new Dog(10);
        dog = dog2;
    }

    public static void main(String[] args) {
        Test test = new Test();
        System.out.println(test.dog);
        test.chageAge(test.dog);
        System.out.println(test.dog);
    }
}

输出结果:

Dog [age=0]
Dog [age=100]


你可能感兴趣的:(Java参数传递方式)