我正准备参加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是Jacket和Jacket的子类实现销售? (我只是在这里猜测。)
Sale var2 = new Sale();
不可能。您无法创建接口类型的对象。
Clothing var3 = new Clothing();
不可能。您无法创建抽象类的对象。
Clothing var4 = new LeatherJacket();
可能,但为什么?
Jacket var5 = new LeatherJacket();
可能,但为什么呢?
LeatherJacket var6 = new Object();
不可能,但为什么不呢?
答案 0 :(得分: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)
答案 1 :(得分:0)
Clothing var4 = new LeatherJacket();
LeatherJacket扩展了延伸服装的夹克。
Jacket var5 = new LeatherJacket();
LeatherJacket扩展了夹克
LeatherJacket var6 = new Object();
Object是所有的超类。你不能这样做但反之亦然对象o = new LeatherJacket();
答案 2 :(得分:0)
当你有这样的层次结构时,你可以通过维恩图来感知它:
以下内容应该为您提供一个非常好的线索:允许和不允许:
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)