本帖最後由 鄭繼威 於 2023-8-16 21:09 編輯
定義一 Family 類別,並且有一建構子Family(String name, int age, String hobby),並在Family類別下建立四個實體物件,分別為man、woman、boy 與 girl。同時,於Family類別下定義3個欄位(name,age,hobby)及 showProfile() 方法用來顯示每位家庭成員的描述,並於 main 方法中呼叫它。
執行參考畫面如下:
- public class Ch02 {
- public static void main(String[] args) {
- Family man = new Family("爸爸", 40, "爬山");
- Family woman = new Family("媽媽", 38, "逛街");
- Family boy = new Family("男孩", 10, "打電動");
- Family girl = new Family("女孩", 8, "看書");
-
- man.showProfile();
- woman.showProfile();
- boy.showProfile();
- girl.showProfile();
-
- }
- }
- class Family
- {
- String name;
- int age;
- String hobby;
-
- Family(String name, int age, String hobby)
- {
- this.name = name;
- this.age = age;
- this.hobby = hobby;
- }
-
- void showProfile()
- {
- System.out.println(this.name + "今年" + this.age + "歲,喜歡" + this.hobby);
- }
-
- void plusAge()
- {
- this.age+=1;
- }
- }
複製代碼 |