Re: [問題] 關於繼承

看板java作者 (foolish)時間19年前 (2006/03/25 11:21), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串6/6 (看更多)
※ 引述《erik777 ( )》之銘言: : 我的觀念不是很清楚... : public class Car : { : private double OILSIZE=30;//油箱總量 : public double output() : { : return OILSIZE; : } : } : public class Coupe extends Car : { : private double OILSIZE=50;//油箱總量 : } : public class Question : { : public static void main(String args[]) : { : Coupe driver = new Coupe();//宣告Coupe物件 : System.out.println(driver.output());//我想讓他印出50... : } : } : Coupe繼承Car類別時不是會連output一起繼承嗎? : 但是為啥他結果印出來的不是OILSIZE = 50而是父類別中的30 : 如果我想要讓他印出50該怎麼做呢? : 一定要做override嗎? ^^^^^^^^^^^^^^^^^^ 請注意, override的定義參閱 http://mindprod.com/jgloss/override.html 看不見依然存在。 class GrandObject { int field = 10; public GrandObject() { System.out.println(this.field); } } class ParentObject extends GrandObject { int field = 20; public ParentObject() { System.out.println(this.field); } } class TheObject extends ParentObject { int field = 30; public TheObject() { System.out.println(this.field); } } public class InvokeChain { public static void main(String[] args) { TheObject o1 = new TheObject(); GrandObject o2 = new TheObject(); System.out.println("Creation Finish. \n"); System.out.println(o1.field); System.out.println(o2.field); ParentObject o3 = o1; System.out.println(o3.field); } } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 210.59.94.148
文章代碼(AID): #149BT9W8 (java)
討論串 (同標題文章)
文章代碼(AID): #149BT9W8 (java)