1. 程式人生 > >Java中值傳遞與引用傳遞

Java中值傳遞與引用傳遞

//Test.java
public class Test {
    public static void main(String[] args)
    {
        Person ps = new Person();
        ps.setPerson(10,"yyy",new Address());
        ps.printPerson();
        Address ad = ps.getAddress();
        String n = ps.getName();
        n = "lll";
        //Person psCopy = ps;
//psCopy.setPerson(11,"llll"); ad.setAddress("Zhenjiang", "HangZhou"); ps.printPerson(); } }
//Person.java

public class Person {

    private int age;
    private String name;
    private Address address;

    public void setPerson(int age, String name, Address address)
    {
        this
.age = age; this.name = name; this.address = address; } public String getName() { return this.name; } public Address getAddress() { return address; } public void printPerson() { System.out.println("name:,"+name); System.out
.println("age:,"+age); address.printAddress(); } }
//Address.java

public class Address {
    private String province;
    private String city;

    public Address()
    {
        province = "ShanDong";
        city = "JiNan";
    }



    public void setAddress(String province, String city)
    {
        this.province = province;
        this.city = city;
    }


    public void printAddress()
    {
        System.out.println("province:," + province);
        System.out.println("city:," + city);
    }
}

輸出結果:
name:,yyy
age:,10
province:,ShanDong
city:,JiNan
name:,yyy
age:,10
province:,Zhenjiang
city:,HangZhou
基本型別(String,int)傳遞的是值,自定義“類”傳遞的是引用。

修改Test.java檔案,再來看一下執行結果

public class Test {
    public static void main(String[] args)
    {
        Person ps = new Person();
        ps.setPerson(10,"yyy",new Address());
        ps.printPerson();
        changObject(ps);
        ps.printPerson();
    }
    public static void changObject(Person ps)
    {
        Address ad = ps.getAddress();
        String n = ps.getName();
        n = "lll";

        ad.setAddress("Zhenjiang", "HangZhou");
    }

}

輸出結果:
name:,yyy
age:,10
province:,ShanDong
city:,JiNan
name:,yyy
age:,10
province:,Zhenjiang
city:,HangZhou
可見函式引數傳遞時也遵照上面的規則。
Java中只有基本資料型別在棧區,自定義類放在堆區。

Person ps;//會在Java IDE報錯
Person ps = new Person();//不會報錯