返回列表 發帖
  1. public class Ch69 {  //主類別

  2.         public static void main(String[] args) {  //主方法
  3.             Dog d1=new Dog("憨憨",2,1.28);  //創建Dog類別的新物件,取名為 d1
  4.             Dog d2=new Dog("球球",1,1.35);
  5.             Cat c1=new Cat("咪咪",3,0.95);
  6.             d1.showProfile();  //執行d1物件的showProfile()方法
  7.             d1.makeSound(2);
  8.             d2.showProfile();
  9.             d2.makeSound(3);
  10.             c1.showProfile();
  11.             c1.makeSound(5);
  12.         }

  13. }

  14. class Animal{    //定義父類別Animal
  15.       
  16.         String name;   //定義Animal的屬性
  17.         int age;
  18.         double weight;
  19.       
  20.         Animal(String n, int a, double w)  //定義Animail的建構子,建構子名稱必須和類別名稱一樣,建構子規範了新物件應有的屬性,透過建構子,快速的把物件初始化。
  21.         {
  22.                 name=n;    //把建構子的參數n指派給此類別所產生的物件,作為它的屬性
  23.                 age=a;    //把建構子的參數a指派給此類別所產生的物件,作為它的屬性
  24.                 weight=w;  //把建構子的參數w指派給此類別所產生的物件,作為它的屬性
  25.         }
  26.       
  27.         void showProfile()  //定義Animal的方法
  28.         {
  29.                 System.out.println(name+"今年"+age+"歲,體重"+weight+"公斤.");
  30.         }      
  31. }

  32. class Dog extends Animal  //定義Dog子類別,它繼承自Animal父類別,所以它具有和Animail一樣的屬性和方法
  33. {
  34.         Dog(String n, int a, double w)   //定義Dog子類別的建構子(建構子不能繼承,所以必須重寫,但可調用父類別的建構子來使用)
  35.         {
  36.                 super(n,a,w);  
  37.         }
  38.         void makeSound(int x)//在Dog子類別中,新增方法
  39.         {
  40.                 for(int i=1; i<=x; i++)
  41.                         System.out.print("汪~");
  42.                 System.out.println();
  43.         }
  44. }

  45. class Cat extends Animal
  46. {
  47.         Cat(String n, int a, double w)
  48.         {
  49.                 super(n,a,w);
  50.         }
  51.         void makeSound(int x)//在Cat子類別中,新增方法
  52.         {
  53.                 for(int i=1; i<=x; i++)
  54.                         System.out.print("喵~");
  55.                 System.out.println();
  56.         }
  57. }
複製代碼
May

TOP

返回列表