返回列表 發帖

物件導向基礎概念 (三)

本帖最後由 tonyh 於 2015-1-24 17:49 編輯

定義一Dog類別, 並定義其建構子, 以建構子生成實體物件.

  1. public class ch59
  2. {
  3.     public static void main(String args[])
  4.     {
  5.         Dog d1=new Dog();   //在Dog類別下,新增一個名為d1的物件
  6.         d1.name="憨憨";
  7.         d1.color="紅棕色";
  8.         d1.age=2;
  9.         d1.w=1.3f;
  10.         Dog d2=new Dog("球球","白色",1,1.2f);
  11.         d1.showProfile();
  12.         d1.makeSound(2);
  13.         d2.showProfile();
  14.         d2.makeSound(3);
  15.     }
  16. }
  17. class Dog
  18. {
  19.     String name;
  20.     String color;
  21.     int age;
  22.     float w;
  23.     Dog()
  24.     {
  25.     }
  26.     Dog(String name, String color, int age, float w)
  27.     {
  28.         this.name=name;
  29.         this.color=color;
  30.         this.age=age;
  31.         this.w=w;
  32.     }
  33.     void showProfile()
  34.     {
  35.         System.out.println(name+"今年"+age+"歲,體重"+w+"公斤,毛色為"+color+".");
  36.     }
  37.     void makeSound(int n)
  38.     {
  39.         for(int i=0; i<n; i++)
  40.             System.out.print("汪~");
  41.         System.out.println();
  42.     }
  43. }
複製代碼
附件: 您需要登錄才可以下載或查看附件。沒有帳號?註冊

返回列表