【问题标题】:How to inherit from multiple base classes in Java? [duplicate]如何从Java中的多个基类继承? [复制]
【发布时间】:2010-01-09 00:30:07
【问题描述】:

可能的重复:
Cheat single inheritance in Java !!
Why is Multiple Inheritance not allowed in Java or C#?
Multiple Inheritance in java.

我知道我们可以使用接口从多个类继承,但也可以继承状态吗?
如何从 2 个类中继承具有定义的方法并将它们放在 Java 中的第三个类中?

【问题讨论】:

标签: java multiple-inheritance


【解决方案1】:

Java 中不允许多重继承。改用委托和接口

public interface AInterface {
        public void a();
}
public interface BInterface {
    public void b();
}

public class A implements AInterface {
    public void a() {}
}
public class B implements BInterface {
    public void b() {}
}

public class C implements AInterface, BInterface {
    private A a;
    private B b;

    public void a() {
        a.a();
    }
    public void b() {
        b.b();
    }
}

从 Java 8 开始,可以在接口中使用 Default Methods

【讨论】:

    【解决方案2】:

    简短的回答:你不能。 Java只有接口的多重继承。

    稍微长一点的答案:如果你确定你关心的方法在接口中,那么你可以有一个实现接口的类,然后委托给“超类”的实例:

    interface Noisy {
      void makeNoise();
    }
    
    
    interface Vehicle {
      void go(int distance);
    }
    
    class Truck implements Vehicle {
      ...
    }
    
    class Siren implements Noisy {
      ...
    }
    
    class Ambulance extends Truck implements Noisy {
      private Siren siren = new Siren();
    
      public makeNoise() {
        siren.makeNoise();
      }
    
      ...
    }
    

    【讨论】:

      【解决方案3】:

      你不能,Java 不支持多重继承。你能做的就是作曲。

      【讨论】:

        【解决方案4】:

        Java 明确禁止实现的多重继承。剩下的就是使用接口和组合来实现类似的结果。

        【讨论】:

        • 劳伦斯提供了一个很好的例子:)
        猜你喜欢
        • 2015-11-16
        • 2013-02-20
        • 1970-01-01
        • 2010-11-24
        • 2012-12-22
        • 2012-06-17
        • 2015-01-23
        • 1970-01-01
        • 2020-06-01
        相关资源
        最近更新 更多