77

I am reading "The Java Tutorial" (for the 2nd time). I just got through the section on Interfaces (again), but still do not understand how Java Interfaces simulate multiple inheritance. Is there a clearer explanation than what is in the book?

3
  • 1
  • This blog post has explained how to achieve multiple inheritance. erik-rasmussen.com/blog/2006/10/23/multiple-inheritance-in-java Aug 24, 2010 at 13:13
  • 3
    @Tom: according to "The Java Tutorial," (4th edition p142) "In Java, a class can inherit from only one class but it can implement more than one interface. Therefore, objects can have multiple types: the type of their own class and the types of all the interfaces that they implement. This means that if a variable is declared to be the type of an interface, its value can reference any object that is instantiated from any class that implements the interface." The author lost me on the last sentence but the explanations here (mostly) cleared it up.
    – jacknad
    Aug 25, 2010 at 5:49

22 Answers 22

158

Suppose you have 2 kinds of things in your domain : Trucks and Kitchens

Trucks have a driveTo() method and Kitchens a cook() method.

Now suppose Pauli decides to sell pizzas from the back of a delivery truck. He wants a thing where he can driveTo() and cook() with.

In C++ he would use multiple inheritance to do this.

In Java that was considered to be too dangerous so you can inherit from a main class, but you can "inherit" behaviors from interfaces, which are for all intents and purposes abstract classes with no fields or method implementations.

So in Java we tend to implement multiple inheritance using delegations :

Pauli subclasses a truck and adds a kitchen to the truck in a member variable called kitchen. He implements the Kitchen interface by calling kitchen.cook().

class PizzaTruck extends Truck implements Kitchen {
   Kitchen kitchen;

   public void cook(Food foodItem) {
      kitchen.cook(foodItem);
   }
}

He is a happy man because he can now do things like ;

pizzaTruck.driveTo(beach);
pizzaTruck.cook(pizzaWithExtraAnchovies);

Ok, this silly story was to make the point that it is no simulation of multiple inheritance, it is real multiple inheritance with the proviso that you can only inherit the contract, only inherit from empty abstract base classes which are called interfaces.

(update: with the coming of default methods interfaces now can also provide some behavior to be inherited)

6
  • 8
    what if Kitchen isn't an interface but another class?
    – Bizmarck
    Apr 15, 2013 at 20:36
  • 2
    @bizmark: Then create an interface Cookery (with public void cook()) that Kitchen and PizzaTruck would both implement.
    – splungebob
    May 15, 2013 at 13:31
  • 10
    What if both Truck and Kitchen are classes with fields and we need all those fields within PizzaTruck? e.g. to implement PizzaTruck.shootPizzasBackwards(), which reduces PizzaCount (A Kitchen field) and increases speed (A Truck field) Jun 24, 2014 at 10:46
  • See composition over inheritance : en.wikipedia.org/wiki/Composition_over_inheritance Jul 15, 2014 at 14:11
  • 1
    While correct in 2010, "...which are for all intents and purposes abstract classes with no fields or method implementations..." is no longer correct, thanks to default methods. Interfaces still don't have instance state, but they do have methods a class can inherit. May 21, 2017 at 17:20
19

You're probably confused because you view multiple inheritance locally, in terms of one class inheriting implementation details from multiple parents. This is not possible in Java (and often leads to abuse in languages where it's possible).

Interfaces allow multiple inheritance of types, e.g. a class Waterfowl extends Bird implements Swimmer can be used by other classes as if it were a Bird and as if it were a Swimmer. This is the the deeper meaning of multiple inheritance: allowing one object to act like it belongs to several unrelated different classes at once.

1
  • 1
    Reinforced by Oracle's docs: docs.oracle.com/javase/tutorial/java/IandI/…. I thank you very much for making the distinction between inheritance of types and the more "traditional" definition of inheritance, which includes implementation. I have been trying to understand how interfaces can be considered a form of multiple inheritance for days, and now it's clear. Java simply uses a different definition of inheritance than I expected. I wish I could give you 61 more upvotes, because I think it is a stronger answer than the currently accepted one.
    – skrrgwasme
    Jan 28, 2015 at 21:45
17

Here is a way to achieve multiple inheritance through interfaces in java.

What to achieve?
class A extends B, C // this is not possible in java directly but can be achieved indirectly.

class B{
   public void getValueB(){}
}

class C{
   public void getValueC(){}
}


interface cInterface{
   public getValueC();
}

class cChild extends C implemets cInterface{
    public getValueC(){

      // implementation goes here, call the super class's getValueC();

    }
}


// Below code is **like** class A extends B, C 
class A extends B implements cInterface{
   cInterface child =  new cChild();
   child.getValueC();
}
1
  • 1
    @challenger When you implement "cInterface", we would need to implement "getValueC()" in class A right?
    – Nick
    Jan 15, 2018 at 7:16
10

given the two interfaces below...

interface I1 {
  abstract void test(int i);
}
interface I2 {
  abstract void test(String s);
}

We can implement both of these using the code below...

public class MultInterfaces implements I1, I2 {
  public void test(int i) {
    System.out.println("In MultInterfaces.I1.test");
  }
  public void test(String s) {
    System.out.println("In MultInterfaces.I2.test");
  }
  public static void main(String[] a) {
    MultInterfaces t = new MultInterfaces();
    t.test(42);
    t.test("Hello");
  }
}

We CANNOT extend two objects, but we can implement two interfaces.

2
  • What if the two methods in I1 & I2 has same type of arguments ?
    – Nivetha T
    Apr 1, 2016 at 5:14
  • Then you'd just have one method, the compiler won't care as they do the same thing. See the answer here stackoverflow.com/questions/2801878/…
    – David
    Apr 4, 2016 at 18:21
10

Interfaces don't simulate multiple inheritance. Java creators considered multiple inheritance wrong, so there is no such thing in Java.

If you want to combine the functionality of two classes into one - use object composition. I.e.

public class Main {
    private Component1 component1 = new Component1();    
    private Component2 component2 = new Component2();
}

And if you want to expose certain methods, define them and let them delegate the call to the corresponding controller.

Here interfaces may come handy - if Component1 implements interface Interface1 and Component2 implements Interface2, you can define

class Main implements Interface1, Interface2

So that you can use objects interchangeably where the context allows it.

5

It's pretty simple. You can implement more than one interface in a type. So for example, you could have an implementation of List that is also an instance of Deque (and Java does...LinkedList).

You just can't inherit implementations from multiple parents (i.e. extend multiple classes). Declarations (method signatures) are no problem.

5
  • Yes, this is why it "simulates" multiple inheritance. Aug 24, 2010 at 13:18
  • 1
    @Erik: it actually implements multiple inheritance, just not multiple inheritance of implementation. Aug 24, 2010 at 13:21
  • @Erick: "Simulates" is only a useful term when you have a preconceived notion of how MI "should be" from another language. Even then it's a destructive thought. It's multiple inheritance, just uniquely done. Aug 24, 2010 at 13:37
  • Well, it inherits the signatures but not the implementation. If you don't like the term "simulated multiple inheritance", how about "partial multiple inheritance" ? It's clearly not the same as full multiple inheritance. It seems to me that the most important part is that if you say "A extends B implements C", you can then have a function that takes a parameter of type C and pass an A to it. C is a perfectly good parameter type declaration, even if it doesn't come with a declaration. You may not get the toy but at least you get the box.
    – Jay
    Aug 24, 2010 at 13:41
  • Actually, I'm going to backpedal on this one. I think it's simpler and more correct if "inheritance" is kept strictly for talking about inheriting implementation. Aug 24, 2010 at 13:50
5

You know what, coming from the perspective of a JavaScript dev trying to understand what the heck is going on with this stuff, I'd like to point out a couple things and somebody please tell me what I'm missing here if I'm way off the mark.

Interfaces are really simple. Stupidly, insanely simple. They're as stupidly, insanely simple as people initially think, which is why there are so many duplicate questions on this exact subject because the one reason to use them has been made unclear by people trying to make more of them than they are and there is widespread misuse in every Java server-side code-base I've ever been exposed to.

So, why would you want to use them? Most of the time you wouldn't. You certainly wouldn't want to use them ALL the time as many seem to think. But before I get to when you would, let's talk about what they're NOT.

Interfaces are NOT:

  • in any way a workaround for any sort of inheritance mechanism that Java lacks. They have nothing to do with inheritance, they never did, and in no way simulate anything inheritance-like.
  • necessarily something that helps you with stuff you wrote, so much as it helps the other guy write something meant to be interfaced by your stuff.

They really are as simple as you think they are on first glance. People misuse stupidly all the time so it's hard to understand what the point is. It's just validation/testing. Once you've written something conforms to an interface and works, removing that "implements" code won't break anything.

But if you're using interfaces correctly, you wouldn't want to remove it because having it there gives the next developer a tool for writing an access layer for another set of databases or web services that they want the rest of your app to continue using because they know their class will fail until they get the 100% complete-as-expected-interface in place. All interfaces do is validate your class and establish that you have in fact implemented an interface as you promised you would. Nothing more.

They're also portable. By exposing your interface definitions you can give people wanting to use your unexposed code a set of methods to conform to in order for their objects to use it correctly. They don't have to implement the interfaces. They could just jot them down on a piece of notepad paper and double-check that. But with the interface you have more of a guarantee nothing is going to try to work until it has a proper version of the interface in question.

So, any interface not likely to ever be implemented more than once? Completely useless. Multiple-inheritance? Stop reaching for that rainbow. Java avoids them for a reason in the first place and composited/aggregate objects are more flexible in a lot of ways anyway. That's not to say interfaces can't help you model in ways that multiple-inheritance allows but it's really not inheritance in any way shape or form and shouldn't be seen as such. It's just guaranteeing that your code won't work until you've implemented all of the methods you established that you would.

4
  • Class inheritance combines two somewhat-orthogonal concepts: (1) the ability for derived classes to use members of the base class as though they were their own; (2) the ability for a variable of base-class type to hold references to objects of any derived type. Aspect #2 is a sufficiently-key part of inheritance that I'd certainly call it "inheritance-like" [especially since aspect #1 is a convenience, but aspect #2 is required for OOP]. The essential purpose of an interfaces is allow code with a reference to a thing which is known to have some functionality, to use that functionality.
    – supercat
    Apr 2, 2013 at 16:40
  • 2 feels more like a key aspect for Java OOP due to other language design constraints more than a key aspect of OOP or inheritance in general. Although I did just discover you can define and inherit constants from an interface in Java and I would call that more than inheritance-like. Apr 2, 2013 at 19:52
  • The "X-is-a-Y" relationship defined by inheritance specifies that code which can accept a reference to a Y should also be able to accept a reference to an X. Of what use would such a relationship be if such substitution were not possible?
    – supercat
    Apr 2, 2013 at 20:27
  • "Once you've written something conforms to an interface and works, removing that "implements" code won't break anything." -> This is false, which is particularly evident when dealing with interfaces that are empty (like in marker interfaces: stackoverflow.com/questions/25850328/marker-interfaces-in-java )
    – hmijail
    Jul 12, 2018 at 8:38
3

It's not a simulation of multiple inheritance. In java you can't inherit from two classes, but if you implements two interfaces "it seems like you inherited from two different classes" because you can use your class as any of your two intefaces.

For example

interface MyFirstInteface{
    void method1();
}
interface MySecondInteface{
    void method2();
}
class MyClass implements MyFirstInteface, MySecondInteface{
    public void method1(){
        //Method 1
    }
    public void method2(){
        //Method 2
    }

    public static void main(String... args){
        MyFirstInterface mfi = new MyClass();
        MySecondInterface msi = new MyClass();
    }
}

This will work and you can use mfi and msi, it seems like a multi inheritance, but it's not because you don't inherit anything, you just rewrite public methods provided by the interfaces.

3

You need to be precise:

Java allows multiple inheritance of interface, but only single inheritance of implementation.

You do multiple inheritance of interface in Java like this:

public interface Foo
{
    String getX(); 
}

public interface Bar
{
    String getY();
}

public class MultipleInterfaces implements Foo, Bar
{
    private Foo foo;
    private Bar bar;

    public MultipleInterfaces(Foo foo, Bar bar)
    {
        this.foo = foo;
        this.bar = bar;
    }

    public String getX() { return this.foo.getX(); }
    public String getY() { return this.bar.getY(); }
}
3

Just by the way, the reason why Java does not implement full multiple inheritance is because it creates ambiguities. Suppose you could say "A extends B, C", and then both B and C have a function "void f(int)". Which implementation does A inherit? With Java's approach, you can implement any number of interfaces, but interfaces only declare a signature. So if two interfaces include functions with the same signature, fine, your class must implement a function with that signature. If interfaces you inherit have functions with different signatures, then the functions have nothing to do with each other, so there is no question of a conflict.

I'm not saying this is the only way. C++ implements true multiple inheritance by establishing precedence rules of which implementation wins. But the authors of Java decided to eliminate the ambiguity. Whether because of a philosophical belief that this made for cleaner code, or because they didn't want to do all the extra work, I don't know.

1
  • Correct me if I'm wrong, but from my understanding C++ also eliminates the ability to add virtual members to a base class without recompiling subclasses, and also forfeits base-class referential identity. If B has virtual member Q, X and Y both inherit B and separately override Q, and Z inherits both X and Y, casting a &Z to a &X and then &B will yield a different result from casting a &Z to a &Y and then &B.
    – supercat
    Jun 16, 2013 at 20:03
2

It's not fair to say that interfaces 'simulate' multiple inheritance.

Sure, your type can implement multiple interfaces and act as many different types polymorphically. However, you obviously won't inherit behaviour or implementations under this arrangement.

Generally look at composition where you think you may need multiple inheritance.

OR A potential solution to achieving something multiple inheritance like is the Mixin interface - http://csis.pace.edu/~bergin/patterns/multipleinheritance.html. Use with care!

2

They don't.

I think that the confusion comes from people believing that implementing an interface constitutes some form of inheritance. It doesn't; the implementation can simply be blank, no behavior is forced by the act or guaranteed through any contract. A typical example is the Clonable-interface, which while alluding to lots of great functionality, which defines so little that's it's essentially useless and potentially dangerous.

What do you inherit by implementing an interface? Bubkes! So in my opinion, stop using the words interface and inheritance in the same sentence. As Michael Borgwardt said, an interface is not a definition but an aspect.

2

You can actually "inherit" from multiple concrete classes if they implement interfaces themselves. innerclasses help you achieve that:

interface IBird {
    public void layEgg();
}

interface IMammal {
    public void giveMilk();
}

class Bird implements IBird{
    public void layEgg() {
        System.out.println("Laying eggs...");
    }
}

class Mammal implements IMammal {
    public void giveMilk() {
        System.out.println("Giving milk...");
    }
}

class Platypus implements IMammal, IBird {

    private class LayingEggAnimal extends Bird {}
    private class GivingMilkAnimal extends Mammal {}

    private LayingEggAnimal layingEggAnimal = new LayingEggAnimal();

    private GivingMilkAnimal givingMilkAnimal = new GivingMilkAnimal();

    @Override
    public void layEgg() {
        layingEggAnimal.layEgg();
    }

    @Override
    public void giveMilk() {
        givingMilkAnimal.giveMilk();
    }

}

2

I'd like to point out something that bit me in the behind, coming from C++ where you can easily inherit many implementations too.

Having a "wide" interface with many methods means that you'll have to implement a lot of methods in your concrete classes and you can't share these easily across implementations.

For instance:

interface Herbivore {
    void munch(Vegetable v);
};

interface Carnivore {
    void devour(Prey p);
}

interface AllEater : public Herbivore, Carnivore { };

class Fox implements AllEater {
   ... 
};

class Bear implements AllEater {
   ...
};

In this example, Fox and Bear cannot share a common base implementation for both it's interface methods munch and devour.

If the base implementations look like this, we'd maybe want to use them for Fox and Bear:

class ForestHerbivore implements Herbivore
    void munch(Vegetable v) { ... }
};

class ForestCarnivore implements Carnivore
    void devour(Prey p) { ... }
};

But we can't inherit both of these. The base implementations need to be member variables in the class and methods defined can forward to that. I.e:

class Fox implements AllEater {
    private ForestHerbivore m_herbivore;
    private ForestCarnivore m_carnivore;

    void munch(Vegetable v) { m_herbivore.munch(v); }
    void devour(Prey p) { m_carnivore.devour(p); }
}

This gets unwieldy if interfaces grow (i.e. more than 5-10 methods...)

A better approach is to define an interface as an aggregation of interfaces:

interface AllEater {
    Herbivore asHerbivore();
    Carnivore asCarnivore();
}

This means that Fox and Bear only has to implement these two methods, and the interfaces and base classes can grow independetly of the aggregate AllEater interface that concerns the implementing classes.

Less coupling this way, if it works for your app.

1

I don't think they do.

Inheritance is specifically an implementation-oriented relationship between implementations. Interfaces do not provide any implementation information at all, but instead define a type. To have inheritance, you need to specifically inherit some behaviors or attributes from a parent class.

I believe there is a question here somewhere specifically about the role of interfaces and multiple inheritance, but I can't find it now...

1

There's really no simulation of multiple inheritance in Java.

People will sometimes say that you can simulate multiple inheritance using Interfaces because you can implement more than one interface per class, and then use composition (rather than inheritance) in your class to achieve the behaviors of the multiple classes that you were trying to inherit from to begin with.

1

If it makes sense in your object model, you can of course inherit from one class and implement 1 or more interfaces as well.

1

There are cases where multiple-inheritance turns to be very handy and difficult to replace with interfaces without writing more code. For example, there are Android apps that use classes derived from Activity and others from FragmentActivity in the same app. If you have a particular feature you want to share in a common class, in Java you will have to duplicate code instead of let child classes of Activity and FragmentsActivity derive from the same SharedFeature class. And the poor implementation of generics in Java doesn't help either because writing the following is illegal:

public class SharedFeature<T> extends <T extends Activity>

...
...
1

There is no support for multiple inheritance in java.

This story of supporting multiple inheritance using interface is what we developers cooked up. Interface gives flexibility than concrete classes and we have option to implement multiple interface using single class. This is by agreement we are adhering to two blueprints to create a class.

This is trying to get closer to multiple inheritance. What we do is implement multiple interface, here we are not extending (inheriting) anything. The implementing class is the one that is going to add the properties and behavior. It is not getting the implementation free from the parent classes. I would simply say, there is no support for multiple inheritance in java.

1

No, Java does not support multiple inheritance. Neither using class nor using interface. Refer to this link for more info https://devsuyed.wordpress.com/2016/07/21/does-java-support-multiple-inheritance

1

I also have to say that Java doesn't support multiple inheritance.

You have to differentiate the meaning between extends and implements keywords in Java. If we use extends, we are actually inheriting the class after that keyword. But, in order to make everything simple, we can't use extends more than once. But you can implement as many Interfaces as you wish.

If you implement an interface, there's a zero chance that you will miss the implementation of all the methods in each interface (Exception: default implementations of interface methods introduced in Java 8) So, you are now fully aware of what is happening with the things that you have embedded to your fresh class.

Why Java doesn't allow multiple inheritance is actually, multiple inheritance makes the code somewhat complex. Sometimes, two methods of parent classes might conflict due to having the same signatures. But if you are forced to implement all the methods manually, you will get the full understanding about what's going on, as I mentioned above. It makes your code more understandable to you.

If you need more info on Java interfaces, check out this article, http://www.geek-programmer.com/introduction-to-java-interfaces/

1

Between two Java class multiple Inheritance directly is not possible. In this case java recommend Use to interface and declare method inside interface and implement method with Child class.

interface ParentOne{
   public String parentOneFunction();
}

interface ParentTwo{
    public String parentTwoFunction();
}

class Child implements ParentOne,ParentTwo{

   @Override
    public String parentOneFunction() {
        return "Parent One Finction";
    }

    @Override
    public String parentTwoFunction() {
        return "Parent Two Function";
    }

    public String childFunction(){
       return  "Child Function";
    }
}
public class MultipleInheritanceClass {
    public static void main(String[] args) {
        Child ch = new Child();
        System.out.println(ch.parentOneFunction());
        System.out.println(ch.parentTwoFunction());
        System.out.println(ch.childFunction());
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.