本帖最後由 許婷芳 於 2019-9-7 16:03 編輯
定義一 Family 類別, 並在Family類別下建立四個實體物件,
分別為dad, mom, boy 與 girl.
並且利用showProfile()方法打印出物件的資訊, 執行參考畫面如下:
- public class Ch04 {
- public static void main(String[] args) {
- Family dad=new Family("爸爸",40,"爬山");
- Family mom=new Family("媽媽",38,"逛街");
- Family boy=new Family("男孩",10,"打電動");
- Family girl=new Family("女孩",8,"看書");
-
- dad.showProfile();
- mom.showProfile();
- boy.showProfile();
- girl.showProfile();
- }
- }
複製代碼- public class Family
- {
- //先宣告Family需要用到的三個屬性;
- //稱謂:name;年紀:age;興趣:hobby;
- String name;
- int age;
- String hobby;
-
- Family(String n, int a, String h)
- {
- this.name=n;
- this.age=a;
- this.hobby=h;
- }
- void showProfile()
- {
- System.out.println(name+"今年"+age+"歲,喜歡"+hobby);
- }
- }
複製代碼 |