值傳遞和引用傳遞的小例子


代碼:

public class Demo {

    public static void main(String[] args) {
        // 引用傳遞示例
        Student student = new Student();
        student.setName("lisi");
        student.setSex("girl");
        new Method().test1(student); // entity的值發生了變化
        System.out.println(student.getName() + "," + student.getSex()); // 輸出結果:zhangSan,boy

        // 值傳遞示例
        // String傳遞的也是引用副本的傳遞,但是因為String為final的,所以和按值傳遞等同的
        String str = new String("123");
        new Method().test2(str); // str的值沒有發生變化
        System.out.println(str); // 輸出結果: 123
    }

}

class Method {

    /**
     * 引用傳遞
     */
    public void test1(Student entity) {
        entity.setName("zhangSan");
        entity.setSex("boy");
    }

    /**
     * 值傳遞
     */
    public void test2(String str) {
        str = "abc";
    }
}

class Student {

    private String name;

    private String sex;

    public Student() {
        super();
    }

    public String getName() {
        return name;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM