JAVA是值传递,并不是引用传递

值传递是方法得到所有参数的拷贝,方法不能修改传递给它的任何参数变脸的内容。
引用传递是方法得到的是对象引用的拷贝,对象引用及其他的拷贝同时引用同一个对象(类型C++中的指针)

public class passByValue {
    public static void main(String[] args) {

        // 方法值作为参数传递
        double percent =10;
        tripleValue(percent);
        System.out.println("percent:"+percent);

        // 方法引用对象值作为参数传递
        Employee employee = new Employee();
        tripleSalary(employee);
        System.out.println(employee.getSalary());

        // 验证java是不是引用传递,如果是则交换成功,否则失败
        Employee a = new Employee("a",200);
        Employee b = new Employee("b",300);
        swap(a,b);
        System.out.println("a:"+a.toString());
        System.out.println("b:"+b.toString());

    }

    public static void tripleValue(double x) {
        x = 3 * x;
    }

    public static void tripleSalary(Employee x){
        x.tripleSalry(200);

    }

    public static void swap(Employee x,Employee y){
        Employee temp = x;
        y= temp;
        x = y;
    }
}

class Employee{
    private  String name ;
    private double salary;

    public void tripleSalry(double salary){
        this.salary = salary * 3;
    }

    public Employee(double salary) {
        this.salary = salary;
    }

    public Employee(String name, double salary) {
        this.name = name;
        this.salary = salary;
    }

    public Employee() {
    }

    public String getName() {
        return name;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", salary=" + salary +
                '}';
    }
}

// 值传递不会改变参数的值
percent:10.0
// 引用对象
600.0
//swap结果为失败
a:Employee{name='a', salary=200.0}
b:Employee{name='b', salary=300.0}

结论:Java对对象采用的不是引用传递,而是值传递

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值