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

  2.         public static void main(String[] args) {
  3.                 Dog d1 = new Dog("憨憨",2,1.28,"棕色");
  4.                 Dog d2 = new Dog("球球",1,1.35,"白色");
  5.                 Cat c1 = new Cat("咪咪",3,0.95);
  6.                 d1.showProfile();
  7.                 d1.makeSound(2);
  8.                 d2.showProfile();
  9.                 d2.makeSound(3);
  10.                 c1.showProfile();
  11.                 c1.makeSound(5);
  12.                
  13.         }

  14. }

  15. class Animal {
  16.         String name;
  17.         int age;
  18.         double weight;
  19.        
  20.         Animal(String name, int age, double weight) {
  21.                 this.name = name;
  22.                 this.age = age;
  23.                 this.weight = weight;
  24.         }
  25.        
  26.         void showProfile() {
  27.                  System.out.println(name + "今年" + age + "歲,體重" + weight + "公斤.");
  28.         }
  29. }

  30. class Dog extends Animal {
  31.         String color;
  32.        
  33.         Dog(String name, int age, double weight, String color) {
  34.                 super(name, age, weight);
  35.                 this.color = color;
  36.         }
  37.        
  38.         void makeSound(int x) {
  39.                 for(int i=1; i<=x; i++)
  40.             System.out.print("汪~");
  41.         System.out.println();
  42.         }
  43.        
  44.         void showProfile() {
  45.                  System.out.println(name + "今年" + age + "歲,體重" + weight + "公斤,毛色為" + color + ".");
  46.         }
  47. }

  48. class Cat extends Animal {
  49.         String color;
  50.        
  51.         Cat(String name, int age, double weight) {
  52.                 super(name, age, weight);
  53.         }
  54.        
  55.         void makeSound(int x) {
  56.                 for(int i=1; i<=x; i++)
  57.                         System.out.print("喵~");
  58.                 System.out.println();
  59.         }
  60. }
複製代碼

TOP

返回列表