返回列表 發帖
  1. public class Ch68 {

  2.     public static void main(String[] args) {
  3.         Dog d1=new Dog("憨憨",2,1.28); //利用Dog子類別,創建一個Dog物件,()內要有它和建構子參數對應的值。
  4.         Dog d2=new Dog("球球",1,1.35);
  5.         Cat c1=new Cat("咪咪",3,0.95);
  6.         d1.showProfile();
  7.         d2.showProfile();
  8.         c1.showProfile();
  9.     }

  10. }

  11. class Animal{       //自建類別
  12.    
  13.     String name;       //定義屬性
  14.     int age;           //定義屬性
  15.     double weight;     //定義屬性
  16.    
  17.     Animal(String n, int a, double w)   //定義建構子,建構子規範了新物件應有的屬性,透過建構子,快速的把物件初始化。
  18.     {
  19.             name=n; //把建構子的參數n指派給此類別所產生的物件,作為它的屬性。
  20.             age=a;  //若建構子的參數名稱和物件定義的屬性名稱一定,則寫成 this.age=age; 以免編繹器分不清。
  21.             weight=w;
  22.     }
  23.    
  24.     void showProfile()  定義物件有個方法,它能輸出一段訊息。
  25.     {
  26.             System.out.println(name+"今年"+age+"歲,體重"+weight+"公斤.");
  27.     }      
  28. }

  29. class Dog extends Animal //定義Dog子類別,繼承自Animal類別
  30. {
  31.     Dog(String n, int a, double w)
  32.     {
  33.             super(n,a,w); // 建構子不能繼承,所以調用Animal建構子使用,以節省程式碼
  34.     }
  35. }

  36. class Cat extends Animal   //定義Cat子類別,繼承自Animal類別
  37. {
  38.     Cat(String n, int a, double w) // 建構子不能繼承,所以調用Animal建構子使用,以節省程式碼
  39.     {
  40.             super(n,a,w);
  41.     }
  42. }
複製代碼
May

TOP

返回列表