3-引用傳遞

1-數組的傳遞引用

/**
    數組引用傳遞
 */
public class ArrayDemo04 {
    public static void main(String[] args) {
        //靜態初始化數組
        int[] arr = {1, 2, 3, 5, 9};

        //傳遞數組引用
        fun(arr);

        //輸出結果
        for(int i=0; i<arr.length; i++){
            System.out.println(arr[i] + ", ");
        }
    }

    //接收數組引用類型
    public static void fun(int[] x){
        x[0] = 6;
    }
}

1-2數組的傳遞引用圖解

2-1 對象引用傳遞

引用數據類型就是指一段堆內存空間能夠同時被多個棧內存空間所指向java

public class Persion {
     String name; //聲明姓名屬性
     int age; //聲明年齡屬性

    public void tell(){ //取的信息方法
        System.out.println("姓名:" + name + ", 年齡:"+ age);
    }

}
public class ClassDemo05 {
    public static void main(String[] args) {
        Persion s1 = new Persion(); //聲明對象,而且實例化
        Persion s2 = null;

        s2 = s1; //將s1的堆內存空間的使用權給s2
        s1.name = "科比"; //設置s1對象的name屬性的內容
        s1.age = 22; //設置s1對象的age屬性

        //設置s2對象的內容,實際上就是設置s1對象的內容
        s2.age = 44;

        //輸出結果
        System.out.println("s1對象中的內容-----");
        s1.tell();

        System.out.println("s2對象中的內容-----");
        s2.tell();
    }
}

2-2面向對象的傳遞引用圖解

2-3面向對象引用傳遞

public class ClassDemo05 {
    public static void main(String[] args) {
        Persion s1 = new Persion(); //聲明對象,而且實例化
        Persion s2 = new Persion(); //聲明對象,而且實例化

        s2 = s1; //將s1的堆內存空間的使用權給s2
        s1.name = "科比"; //設置s1對象的name屬性的內容
        s1.age = 22; //設置s1對象的age屬性

        s2.name = "杜蘭特"; //設置s2對象的name屬性內容
        s2.age = 20; //設置s2的age屬性內容

        s2 = s1; //將s1的引用傳遞給s2

        //輸出結果
        System.out.println("s1對象中的內容-----");
        s1.tell();

        System.out.println("s2對象中的內容-----");
        s2.tell();
    }
}

2-4面向對象的傳遞引用圖解

相關文章
相關標籤/搜索