Java [duplicate]中多重继承的示例

问题描述 投票:-2回答:1

此问题已经在这里有了答案:

示例1:

package innerclasses;

class D { 

}

abstract class E {

}

class Z extends D {
   E makeE( ){
      return new E( ) { //Anonymous inner class. Class Z extends D & E. 
                        //Ques 1. Isn't this multiple inheritance in //Java?

      };
   }
}

public class MultiImplementation {
   static void takesD(D  d){ }
   static void takesE(E  e){ }
   public static void main(String[] args){
     Z z = new Z();
     takesD(z);
     takesE(z.makeE( ));
   }

}

示例2:

public class Parcel3{
   class Contents {
     private int i = 11;
     public int value(){ return i; }
   }
   class Destination {
      private String label;
      Destination(String whereTo){
        label = whereTo;
      }
      String readLabel( ){
         return label;
      }
      public static void main(String[] args){
         Parcel3 p = new Parcel3();
         //Must use an instance of outerclass
         // to create an instance of the inner class. 
         // Question 2. So, Doesn't this mean Java supports multiple //inheritance
         Parcel3.Contents c = p.new Contents( ); //Q3. Is this only from //Java 8?
         Parcel3.Destination d = p.new Destination("Tasmania");
      }
   }
}

请回答评论中提出的所有问题。这两个示例均摘自Bruce Eckel的“ On Java 8”一书。 enter image description here

问题4:多重继承是否必须始终是A类扩展B,C,D的?在编程世界中,它仅被称为多重继承吗?

java java-8 multiple-inheritance inner-classes
1个回答
1
投票

多重继承的问题是,任何人都不可能知道继承了什么变量或方法,这被称为diamond problem。如果您查看图片,由于它们是相同的,因此无法确定是否在助教上调用了Student或Faculty的方法。

在您的示例中不会发生此问题,因为那里没有一个类继承了多个类。Z类仅扩展D并通过方法返回E的对象。您的第二个示例也不是多重继承,因为内部类位于该类内部,它们不是其父级。

© www.soinside.com 2019 - 2024. All rights reserved.