Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple inheritance on Java interfaces

I thought multiple inheritance was always illegal in Java, but this code compiles:

public interface A {   void a(); }  public interface B {   void b(); }  public interface AB extends A, B { } 

Would having an empty interface such as AB be considered a bad practice? Is there a way to achieve something similar while avoiding the empty interface (using generics or otherwise)?

Note: I'm not asking how to simulate multiple inheritance via interfaces. I realize I could do the following:

public class AbImpl implements A, B {   public void a() {}   public void b() {} } 

For various reasons I need an interface that has both methods.

like image 482
Jacob Wallace Avatar asked Nov 14 '12 23:11

Jacob Wallace


People also ask

Is multiple inheritance allowed in interface?

Java allows multiple inheritance using interfaces. Interfaces could only define abstract methods, that is, methods without any implementation. So if a class implemented multiple interfaces with the same method signature, it was not a problem. The implementing class eventually had just one method to implement.

Can we inherit multiple interfaces in Java?

Components can inherit multiple interfaces, though. Inheriting multiple interfaces isn't problematic, since you're simply defining new method signatures to be implemented.

Can we implement multiple inheritance in Java by interface How?

In the concrete class implementing both interfaces, you can implement the common method and call both super methods. thus You can achieve multiple inheritance in Java using interfaces.

Can inheritance be applied between interfaces?

Also, it is possible for a java interface to inherit from another java interface, just like classes can inherit from other classes. You specify inheritance using the extends keyword. Inheritance will be further discussed below. But unlike classes, interfaces can actually inherit from multiple interfaces.


2 Answers

Multiple inheritance of implementations is not allowed. Components can inherit multiple interfaces, though.

Inheriting multiple interfaces isn't problematic, since you're simply defining new method signatures to be implemented. It's the inheritance of multiple copies of functionality that is traditionally viewed as causing problems, or at the very least, confusion (e.g., the diamond of death).

like image 140
Brian Agnew Avatar answered Sep 18 '22 22:09

Brian Agnew


An interface can extend one or more other interfaces. You can also implement more than one interface in your classes. It is legal because interface is only contract - there is no implementation. You're simply defining a contract for what a class is able to do, without saying anything about how the class will do it.

like image 21
Maciej Ziarko Avatar answered Sep 19 '22 22:09

Maciej Ziarko