返回列表 發帖
  1. package ch02;

  2. public class ch02 {

  3.         public static void main(String[] args) {
  4.                 Dog d1=new Dog("憨憨",2,1.28,"棕色");
  5.                 Dog d2=new Dog("球球",1,1.35,"白色");
  6.                 Cat c1=new Cat("咪咪",3,0.95);

  7.                 d1.showProfile();
  8.                 d1.makeSound(2);
  9.                 d2.showProfile();
  10.                 d2.makeSound(3);      
  11.                 c1.showProfile();
  12.                 c1.makeSound(5);
  13.         }

  14. }
  15. class Animal{
  16.         String name;
  17.         int age;
  18.         double weight;

  19.         Animal(String n,int a,double w){
  20.                 name=n;
  21.                 age=a;
  22.                 weight=w;
  23.         }

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

  49.         void makeSound(int x)
  50.         {
  51.                 for(int i=1; i<=x; i++)
  52.                         System.out.print("喵~");
  53.                 System.out.println();
  54.         }
  55. }
複製代碼

TOP

返回列表