2016-12-15 192 views
0

我正準備參加java考試。請看下面兩個練習(我有解決方案,但解決方案沒有解釋),所以如果有人能檢查我的解釋,那將不勝感激。靜態和動態類型

1)

public interface Sale{} 
public abstract class Clothing{} 
public class Jacket extends Clothing implements Sale{} 
public class LeatherJacket extends Jacket{} 

下列哪項是可能的:

Sale var1 = new LeatherJacket(); 

是可能的,因爲LeatherJacket是外套的子類,夾克實現銷售? (我只是猜測在這裏)。

Sale var2 = new Sale(); 

不可能。您不能創建接口類型的對象。

Clothing var3 = new Clothing(); 

不可能。你不能創建一個抽象類的對象。

Clothing var4 = new LeatherJacket(); 

可能,但爲什麼?

Jacket var5 = new LeatherJacket(); 

可能,但爲什麼呢?

LeatherJacket var6 = new Object(); 

不可能,但爲什麼不呢?

回答

0
Clothing var4 = new LeatherJacket(); 

LeatherJacket延伸延伸服裝的夾克。

Jacket var5 = new LeatherJacket(); 

LeatherJacket擴展夾克

LeatherJacket var6 = new Object(); 

對象是所有的超類。你不能這樣做,但反之亦然yes Object o = new LeatherJacket();

1
Clothing var4 = new LeatherJacket(); 

可能的,但爲什麼呢?

這是允許的,因爲LeatherJacket是派生類Clothing。它是而不是通過抽象類Clothing實例化。它寫了new LeatherJacket()而不是new Clothing()


Jacket var5 = new LeatherJacket(); 

可能的,但到底爲什麼?

這是允許的,因爲所有的皮夾克都是夾克。但相反是不真實的。它像所有的獅子的動物,那麼你可以把它寫成:

Animal lion = new Lion(); //where Lion extends Animal 

但你不能把它寫成:

Lion lion = new Animal(); //not all animals are lions 

LeatherJacket var6 = new Object(); 

不可能的,但爲什麼不?

原因與前面的解釋相同。 Object在Java中處於最高級別,每個類都是類Object的子類。因此,在層次結構的頂部,這是不允許的。然而,這將被允許:

Object var6 = new LeatherJacket(); //allowed (all leather jackets are objects) 
LeatherJacket var 6 = new Object(); //not allowed (not all objects are leather jackets) 
+0

謝謝你的詳細答案。所以在第一個中,var1是Sale類型的變量,它存儲了LeatherJacket的對象,對吧?那麼以下也必須是正確的:Sale var7 = new Jacket();? – DerDieDasEhochWas

+0

@DerDieDasEhochWas是的,你對兩個假設都是正確的。如果有幫助,您可以通過單擊解決方案旁邊空心的勾子來接受來自這裏的** one **解決方案,這對您最有幫助。 – user3437460

0

當你有這樣的層次,你可以通過維恩圖見得:

enter image description here

下應該給你一個很好的線索是允許和不允許的:

Object o = new Clothing();  //not allowed (Clothing is abstract!) 
Object o = new Jacket();   //allowed (jacket is a subset of object) 
OBject o = new LaatherJacket(); //allowed (leather jacket is a subset of object) 

Clothing c = new Object();  //not allowed (Object is not a subset of clothing, cannot assume object is definitely a Clothing) 
Clothing c = new Jacket();  //allowed (jacket is a subset of Clothing) 
Clothing c = new LaatherJacket(); //allowed (leather jacket is a subset of Clothing) 

Jacket j = new Object();   //not allowed (Object is not a subset of jacket, cannot assume object is definitely a jacket) 
Jacket j = new Clothing();  //not allowed (Clothing is abstract!) 
Jacket j = new LeatherJacket(); //allowed (leather jacket is a subset of jacket) 

LeatherJacket j = new Object;  //not allowed (Object is not a subset of jacket, cannot assume object is definitely a leather jacket) 
LeatherJacket j = new Clothing(); //not allowed (Clothing is abstract!) 
LeatherJacket j = new Jacket(); //not allowed (Jacket is not a subset of jacket, cannot assume jacket is definitely a leatherjacket)