"java語言中只有值傳遞,沒有引用傳遞"的理解

來源:互聯網
上載者:User

標籤:ret   結果   assert   style   一個   nbsp   add   虛擬   回收   

建立一個類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;    }}

輸出結果

020

(1).值傳遞:傳遞的是值的拷貝。也就是說傳遞後就不互相關了。 

堆和棧的區別: 
(1).棧:棧存放的是基礎資料型別 (Elementary Data Type)(基礎資料型別 (Elementary Data Type)包括:int、short、double、long、float、boolean、char、byte;注意沒有String)以及對象的引用。 
(2).堆:堆記憶體用來存放由new建立的對象和數組。在堆中分配的記憶體,由Java虛擬機器的自動記憶體回收行程來管理。

當傳遞參數為對象時,傳遞的是對象的引用,存在於棧中,而對象的屬性存在於堆中,修改屬性值,對象的引用不變,

所以本質還是值傳遞;

 

"java語言中只有值傳遞,沒有引用傳遞"的理解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.