How to inherit from multiple base classes in Java? [duplicate]

拈花ヽ惹草 提交于 2020-01-27 19:44:04

问题


Possible Duplicates:
Cheat single inheritance in Java !!
Why is Multiple Inheritance not allowed in Java or C#?
Multiple Inheritance in java.

I know that we can use interfaces to inherit from multiple classes but is it possible to inherit the state as well?
How can I inherit methods with definitions from 2 classes and have them in a third class in Java?


回答1:


Multiple inheritance is not allowed in Java. Use delegates and interfaces instead

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();
    }
}

Since Java 8 it's possible to use Default Methods in Interfaces.




回答2:


Short answer: You can't. Java only has multiple inheritance of interfaces.

Slightly longer answer: If you make sure the methods you care about are in interfaces, then you can have a class that implements the interfaces, and then delegates to instances of the "super classes":

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:


You can not, Java doesn't support multiple inheritance. What you could do is composition.




回答4:


Java explicitly disallows multiple inheritance of implementation. You're left with using interfaces and composition to achieve similar results.



来源:https://stackoverflow.com/questions/2031759/how-to-inherit-from-multiple-base-classes-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!