2016-12-15 191 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)