How do Java Interfaces simulate multiple inheritance?
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?
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.
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.
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...
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.
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.
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.
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 Birdand 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.
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 ;
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)
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(); }
}
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.
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.
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();
}
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.
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>
...
...
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.
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:
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.
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.
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());
}
}