那麼我知道我的問題不是很清楚。袒護我一分鐘。從對象的角度來看,子類是否等同於他們的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編譯器如何理解這一點?感謝幫助 !
'Article'是'TV'所以基類對象可以容納參考通過基礎類 – dbw
擴展爲什麼shouldn't它編譯子類的基類?根據你的定義,一個'TV'也是一個'Article',所以你可以在一個定義爲'Article'的變量中分配一個'TV'的實例。 – SomeJavaGuy