返回列表 發帖

建構子 (二)

  1. //建構子, 又稱建構函式, 是產生物件實體時會自動執行的函式
  2. public class ch77
  3. {
  4.     public static void main(String args[])
  5.     {
  6.          Dog d1=new Dog(8);
  7.          Dog d2=new Dog(10);
  8.          System.out.println("第1隻狗"+d1.getAge()+"歲");
  9.          System.out.println("第2隻狗"+d2.getAge()+"歲");
  10.          
  11.          Dog d3=new Dog();
  12.          d3.setAge(12);
  13.          System.out.println("第3隻狗"+d3.getAge()+"歲");
  14.     }
  15. }

  16. class Dog
  17. {
  18.     int age;

  19.     public Dog()          //無參數的建構子
  20.     {

  21.     }

  22.     public Dog(int def)   //帶有一個整數參數的建構子(建構函式)
  23.     {
  24.          this.age=def;     //當前類別裡的age變數
  25.     }

  26.     public int getAge()
  27.     {
  28.          return age;
  29.     }

  30.     public void setAge(int age)
  31.     {
  32.          this.age=age;
  33.     }
  34. }
複製代碼

返回列表