物件導向中new的一些差異(地址)

package tw.xxx.xxx.copy.oop;

 

class Shirt{

   int price = 1000;

   String color= "red";

   //以上為預設設定,當你說要產生一件衣服時如果不指定的話,就會是一件價格1000的紅衣服

}

 

public class TestReferenceOperateEx1 {

 

   public static void main(String[] args) {

      Shirt myShirt = new Shirt();

      //產生一件新衣服(等號右邊),取名叫myShirt並告訴java這是一件衣服類別的物件(等號右邊)

      System.out.println("預設衣服顏色為:"+myShirt.color);

      System.out.println("預設衣服價格為:"+myShirt.price);

      //因為我沒有設定過,所以他會使用預設值(red1000)

      System.out.println(myShirt);

      //這一行會印出myShirt這個我新產生的衣服(物件)他的存放位置(記憶體中的地址)

     

      Shirt yourShirt = new Shirt();

      System.out.println(yourShirt);

      //對照上面,因為我又new了一件新衣服(是你的),當然跟我的衣服不是同一件(不是同一個物件),擁有不同存放位置(記憶體中的地址)

 

      System.out.println("-------------------------------");

     

      //接下來把預設值改掉,大家改成自己喜歡的衣服顏色跟價格

     

      myShirt.color="yellow";

      myShirt.price=500;

     

      yourShirt.color="green";

      yourShirt.price=1500;

     

      System.out.println("myShirt衣服顏色為:"+myShirt.color);

      System.out.println("myShirt衣服價格為:"+myShirt.price);

      System.out.println("yourShirt衣服顏色為:"+yourShirt.color);

      System.out.println("yourShirt衣服價格為:"+yourShirt.price);

      System.out.println("-------------------------------");

      //大家的衣服果然都不一樣了,因為是兩個物件,所以可以有各自的顏色與價格

     

      yourShirt = myShirt;//這一行說,把yourShirt原本連結的地址換掉,改成myShirt的。也就是把你的衣服丟掉拿我的

      //所以現在yourShirt myShirt共用一件衣服(一個物件、一個地址)

      //因此,改了myShirtyourShirt也會被改

     

      myShirt.price = 0;

      //改了myShirt的價格

      System.out.println("yourShirt衣服價格為:"+yourShirt.price);//發現yourShirt的價格也被改了

      System.out.println("-------------------------------");

      System.out.println("myShirt地址;"+myShirt);

      System.out.println("yourShirt地址;"+yourShirt);

      //地址變成一樣的了

   }

}


預設衣服顏色為:red
預設衣服價格為:1000
tw.xxx.xxx.copy.oop.Shirt@139a55
tw.xxx.xxx.copy.oop.Shirt@1db9742
-------------------------------
myShirt衣服顏色為:yellow
myShirt衣服價格為:500
yourShirt衣服顏色為:green
yourShirt衣服價格為:1500
-------------------------------
yourShirt衣服價格為:0
-------------------------------
myShirt地址;tw.xxx.xxx.copy.oop.Shirt@139a55
yourShirt地址;tw.xxx.xxx.copy.oop.Shirt@139a55

 



無限制參數類別的寫法 

package tw.xxx.xxx.copy.oop;

 

public class TestVarArgsEx1 {

   public void sum(String str,int...num){//重點就是那個「...」代表放幾個數字都可以,但是一個方法只能使用varargs(也就是"...")一次,並且需要放在最後面

      int sum=0;

      for(int n:num){

          sum=sum+n;

      }

      System.out.println(str+sum);

   }

   public static void main(String[] args) {

      TestVarArgsEx1 test = new TestVarArgsEx1();

      test.sum("總和為:", 123,456,333,777,8,12,88);

   }

}


總和為:1797

arrow
arrow
    全站熱搜

    乙方 發表在 痞客邦 留言(0) 人氣()