返回列表 發帖
本帖最後由 董宸佑 於 2020-11-6 21:03 編輯
  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.                 d1.showProfile();
  6.                 d2.showProfile();
  7.                 Cat c1=new Cat("咪咪",3,1.5f);
  8.                 c1.showProfile();  
  9.                 System.out.println("總共有"+Dog.sum+"隻狗,"+Cat.sum+"隻貓.");            
  10.         }

  11. }

  12. class Dog
  13. {
  14.     static int sum=0;
  15.         String name;
  16.         int age;
  17.         float w;

  18.         Dog(String n,int a,float w)
  19.         {
  20.                 sum++;
  21.                 name=n;
  22.                 age=a;
  23.                 this.w=w;
  24.         }

  25.         void showProfile()
  26.         {
  27.                  System.out.println(name+"今年"+age+"歲,體重"+w+"公斤.");
  28.         }
  29. }

  30. class Cat
  31. {
  32.         static int sum=0;
  33.         String name;
  34.         int age;
  35.         float w;
  36.         Cat(String n,int a,float w)
  37.         {
  38.                 sum++;
  39.                 name=n;
  40.                 age=a;
  41.                 this.w=w;
  42.         }

  43.         void showProfile()
  44.         {
  45.                  System.out.println(name+"今年"+age+"歲,體重"+w+"公斤.");
  46.         }       
  47. }
複製代碼

TOP

返回列表