2016-01-21 28 views
0

那麼我知道我的問題不是很清楚。袒護我一分鐘。從對象的角度來看,子類是否等同於他們的racine類?

我創建了3抽象類:

類文章:媽媽級

public abstract class Article{ 
    //myPrivate Var Declarations 
    public Article(long reference, String title, float price, int quantity){ 
     this.reference = reference; 
     this.title  = title; 
     this.price  = price; 
     this.quantity = quantity; 
    } 
} 

類Electromenager:第一個孩子

public abstract class Electromenager extends Article{ 
    //myVar declarations 
    public Electromenager(long reference, String title, float price, int quantity, int power, String model) { 
     super(reference, title, price, quantity); 
     this.power = power; 
     this.model = model; 
    } 
} 

類ALIMENTAIRE:第

的另一個孩子
public abstract class Alimentaire extends Article{ 
    private int expire; 
    public Alimentaire(long reference, String title, float price, int quantity,int expire){ 
     super(reference, title, price, quantity); 
     this.expire = expire; 
    } 
} 

那麼,就讓我們假設這些類必須是抽象的,所以基本上在主類,我不能直接實例化它們的對象這樣做的,我們需要做一些基本的擴展..:

class TV extends Electromenager { 
    public TV(long reference, String title, float price, int quantity, int power, String model){ 
     super(reference,title,price,quantity,power,model); 
    } 
} 
class EnergyDrink extends alimentaire { 
    public EnergyDrink(long reference, String title, float price, int quantity,int expire){ 
     super(reference,title,price,quantity,expire); 
    } 
} 

所以在這裏我的困惑開始發生!當寫在主():

Article art   = new TV (145278, "OLED TV", 1000 , 1 ,220, "LG"); 
EnergyDrink art2 = new EnergyDrink (155278 , "Eau Miniral" , 6 , 10, 2020); 

令人驚訝的是,我得到零誤差!不應該輸入::

TV art   = new TV (145278, "OLED TV", 1000 , 1 ,220, "LG"); 
//instead of 
Article art  = new TV (145278, "OLED TV", 1000 , 1 ,220, "LG"); 

爲什麼這兩種書寫都是正確的?以及java編譯器如何理解這一點?感謝幫助 !

+1

'Article'是'TV'所以基類對象可以容納參考通過基礎類 – dbw

+0

擴展爲什麼shouldn't它編譯子類的基類?根據你的定義,一個'TV'也是一個'Article',所以你可以在一個定義爲'Article'的變量中分配一個'TV'的實例。 – SomeJavaGuy

回答

2

子類有自己的基類的所有功能。

按說

Article art   = new TV (145278, "OLED TV", 1000 , 1 ,220, "LG"); 

聲明art作爲第二十對象,這是沒有錯的。如果不投射,您將無法訪問純電視功能。 無論如何,一個新的電視對象是創建。如果你投它:

TV tv   = (TV) art; 

不會有任何問題,你可以訪問所有的電視功能。

更普遍,甚至

Object object = new TV (145278, "OLED TV", 1000 , 1 ,220, "LG"); 

會工作。

+0

好了,我不知道我們可以投對象,以得到包容性的方法...... 讓我們想象的電視有一個名爲方法: 'changeModel(字符串型);' 此: '條藝術=新的電視(145278, 「OLED電視」,1000,1,220, 「LG」);' 不會讓我寫:art.changeModel( 「QHD」); ? 和一個問題,什麼是藝術條/電視藝術/ Object對象? 。 是否表示我聲明,我在使用新的操作符的存儲器中創建一個對象的引用(有點像一個指針)? 爲什麼我不能例如寫: 'EnergyDrink技術=新TV(145278, 「OLED TV」,1000,1,220, 「LG」); '? –

2

你需要考慮行Article art = new TV (145278, "OLED TV", 1000 , 1 ,220, "LG");

在兩個獨立的步驟

  1. 創建TV類型的Object使用new操作
  2. 聲明Article類型的引用類型變量art和分配TV在步驟#1中創建的對象

您在步驟1調用TV類型的有效構造,自ArticleTV父母這樣分配是有效的太在步驟2中

相關問題