"java语言中只有值传递,没有引用传递"的理解

创建一个类Human

public class Human {
    private int age;
    private int sex;//0-女,1-男
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public int getSex() {
        return sex;
    }
    public void setSex(int sex) {
        this.sex = sex;
    }
}

测试类

class HumanTest {

    @Test
    void test() {
        Human human=new Human();
        int age=human.getAge();
        addage(age);
        System.out.println(age);
        
        man(human);
        System.out.println(human.getAge());
        assert human.getSex()==1;
        
    }
    void man(Human human) {
        human.setAge(20);
        human.setSex(1);
    }
    void addage(int age) {
        age+=2;
    }
}

输出结果

0
20

(1).值传递:传递的是值的拷贝。也就是说传递后就不互相关了。 

堆和栈的区别: 
(1).栈:栈存放的是基本数据类型(基本数据类型包括:int、short、double、long、float、boolean、char、byte;注意没有String)以及对象的引用。 
(2).堆:堆内存用来存放由new创建的对象和数组。在堆中分配的内存,由Java虚拟机的自动垃圾回收器来管理。

当传递参数为对象时,传递的是对象的引用,存在于栈中,而对象的属性存在于堆中,修改属性值,对象的引用不变,

所以本质还是值传递;

猜你喜欢

转载自www.cnblogs.com/corexy/p/9467339.html
今日推荐