返回列表 發帖

建構子 (一)

  1. //建構子, 又稱建構函式, 是產生物件實體時會自動執行的函式
  2. public class ch76
  3. {
  4.     public static void main(String args[])
  5.     {
  6.          Dog d1=new Dog(8);   //呼叫建構函式
  7.          System.out.println(d1.getAge()+"歲");
  8.          d1.setAge(10);       //設定為10
  9.          System.out.println(d1.getAge()+"歲");
  10.     }
  11. }

  12. class Dog
  13. {
  14.     int age;

  15.     public Dog(int def)   //帶有一個整數變數的建構子(建構函式)
  16.     {
  17.          this.age=def;     //當前類別裡的age變數
  18.     }

  19.     public int getAge()
  20.     {
  21.          return age;
  22.     }

  23.     public void setAge(int age)
  24.     {
  25.          this.age=age;
  26.     }
  27. }
複製代碼

返回列表