本帖最後由 鄭繼威 於 2023-2-11 11:57 編輯
定義一 Family 類別,並在Family類別下建立四個實體物件,分別為man、woman、boy 與 girl。同時,於Family類別下定義 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.plusage(20);
-
- 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);
- }
-
- int plusage(int n)
- {
- this.age += n;
- return this.age;
- }
- }
複製代碼本帖隱藏的內容需要積分高於 1 才可瀏覽 |