17

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?

Community
  • 1
  • 1
Anonymous
  • 4,133
  • 10
  • 31
  • 38
  • Possible duplicates: http://stackoverflow.com/questions/1262447/multiple-inheritance-in-java, http://stackoverflow.com/questions/1038314/alternative-of-multiple-inheritance-in-java, http://stackoverflow.com/questions/995255/why-is-multiple-inheritance-not-allowed-in-java-or-c, http://stackoverflow.com/questions/70537/cheat-single-inheritance-in-java, etc, etc. – Pascal Thivent Jan 09 '10 at 00:37
  • Those other questions are not duplicates IMO. Those questions ask *why* there is no multiple inheritance. This question asks how to get around it -- with suitable answers provided that the other questions do not provide. – Dave Aug 12 '14 at 15:43

4 Answers4

28

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.

L12
  • 85
  • 1
  • 7
Fabiano
  • 5,124
  • 6
  • 42
  • 69
26

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

  ...
}
Laurence Gonsalves
  • 137,896
  • 35
  • 246
  • 299
3

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

albertein
  • 26,396
  • 5
  • 54
  • 57
2

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

Rob Oxspring
  • 2,835
  • 1
  • 22
  • 28