Re: [問題] 關於繼承
※ 引述《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
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 6 之 6 篇):
java 近期熱門文章
PTT數位生活區 即時熱門文章