其他分享
首页 > 其他分享> > 方法-参数传递

方法-参数传递

作者:互联网

方法-参数传递

参数传递:值传递

传递基本数据类型时:把实参的值传递给形参

package com.gcbeen.method;

/**
 * @author gcbeen
 * 
 */
public class HomeWork01 {
    private static int x = 10;

    public static void updataeValue(int value) {
        value = 3 * value;
        System.out.println("value的值:" + value);
    }

    public static void main(String[] args) {
        System.out.println("调用前的值:" + x);
        updataeValue(x);
        System.out.println("调用后的值:" + x);
    }

}



// 调用前的值:10
// value的值:30
// 调用后的值:10

// Process finished with exit code 0

分析

传递引用数据类型时:把实参引用的值 传递给形参

package com.gcbeen.method;

/**
 * @author gcbeen
 * 
 */
public class User {
    private String name;
    private int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
package com.gcbeen.method;

/**
 * @author gcbeen
 * 
 */
public class HomeWork02 {

    public static void updateUser(User student) {
        student.setName("lishen");
        student.setAge(22);
    }

    public static void main(String[] args) {
        User user = new User("zhangsan", 20);
        System.out.println("调用user前的值:" + user.getName() + "," + user.getAge());
        updateUser(user);
        System.out.println("调用user后的值:" + user.getName() + "," + user.getAge());
    }
}

在这里插入图片描述

分析

下面我们通过一个反例来说明

package com.gcbeen.method;

/**
 * @author gcbeen
 * 
 */
public class HomeWork03 {

    /**
     * 交换两个对象
     * @param x
     * @param y
     */
    public static void swap(User x, User y) {
        User temp = x;
        x = y;
        y = temp;
    }

    public static void main(String[] args) {
        User user = new User("user", 26);
        User stu = new User("stu", 18);
        System.out.println("调用前user的值:" + user.getName() + "," + user.getAge());
        System.out.println("调用前stu的值:" + stu.getName() + "," + stu.getAge());
        swap(user, stu);
        System.out.println("调用后user的值:" + user.getName() + "," + user.getAge());
        System.out.println("调用后stu的值:" + stu.getName() + "," + stu.getAge());
    }

}

// 调用前user的值:user,26
// 调用前stu的值:stu,18
// 调用后user的值:user,26
// 调用后stu的值:stu,18

// Process finished with exit code 0

在这里插入图片描述

标签:调用,引用,参数传递,stu,user,方法,public,User
来源: https://www.cnblogs.com/gcbeen/p/16683726.html