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

  2.         public static void main(String[] args) {
  3.                 Dog d1=new Dog("憨憨", 2, 1.3f, "紅棕色");
  4.                 Dog d2=new Dog("球球", 1, 1.2f, "白色");
  5.                 Cat c1=new Cat("咪咪", 3, 1.5f, "銀灰色");
  6.                 d1.showProfile();
  7.                 d1.makeSound(2);
  8.                 d2.showProfile();
  9.                 d2.makeSound(3);
  10.                 c1.showProfile();
  11.                 c1.makeSound(5);
  12.                 System.out.println("總共有"+Dog.sum+"隻狗,"+Cat.sum+"隻貓.");
  13.         }      
  14. }

  15. class Dog
  16. {
  17.             static int sum=0;
  18.         String name;
  19.         int age;
  20.         float w;
  21.         String color;

  22.         Dog(String n,int a,float w,String c)
  23.         {
  24.                     sum++;
  25.                 name=n;
  26.                 age=a;
  27.                 this.w=w;
  28.                 color=c;
  29.         }

  30.         void showProfile()
  31.         {
  32.                 System.out.println(name+"今年"+age+"歲,體重"+w+"公斤,毛色為"+color+".");
  33.         }
  34.         
  35.         void makeSound(int n)
  36.         {
  37.                 for(int i=1; i<=n; i++)
  38.                         System.out.print("汪~");
  39.                 System.out.println("");
  40.         }
  41. }

  42. class Cat
  43. {
  44.                 static int sum=0;
  45.                 String name;
  46.                 int age;
  47.                 float w;
  48.                 String color;
  49.                
  50.                 Cat(String n,int a,float w,String c)
  51.         {
  52.                                 sum++;
  53.                 name=n;
  54.                 age=a;
  55.                 this.w=w;
  56.                 color=c;
  57.         }

  58.         void showProfile()
  59.         {
  60.                 System.out.println(name+"今年"+age+"歲,體重"+w+"公斤,毛色為"+color+".");
  61.         }
  62.         
  63.         void makeSound(int n)
  64.         {
  65.                 for(int i=1; i<=n; i++)
  66.                         System.out.print("喵~");
  67.                 System.out.println("");
  68.         }
  69. }
複製代碼

TOP

返回列表