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.
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.
Components can inherit multiple interfaces, though. Inheriting multiple interfaces isn't problematic, since you're simply defining new method signatures to be implemented.
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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With