Appearance
Extending from two classes
In Java, a class can only extend from one superclass (i.e., it can only have one direct parent class). This means that if you want to combine functionality from two classes, you need to use one of the following approaches:
- Multiple inheritance of classes is not supported: In this case, one class would extend from two other classes. This is not allowed in Java because it can lead to the "diamond problem", where a subclass inherits conflicting implementations of a method from its two superclasses.
java
// NOT ALLOWED IN JAVA
public class C extends A, B { // syntax error
// ...
}- Use single inheritance and implement interfaces: In this case, one class extends from one class and implements an interface. This is allowed in Java because an interface does not provide concrete implementation, so there is no risk of the "diamond problem".
java
public class C extends A implements B {
// ...
}- Use single inheritance and delegate methods: In this case, one class extends from one class and has an instance variable for the other class. The subclass can then delegate the methods it needs to the instance variable.
java
public class C extends A {
private B b;
public C(B b) {
this.b = b;
}
public void someMethod() {
b.someMethod(); // delegation
}
}Keep in mind that these are just basic examples, and you may need to handle other issues such as constructor inheritance and method conflicts in your actual implementation. Note that Java 8+ allows default methods in interfaces, which can sometimes reintroduce diamond problem conflicts that must be explicitly resolved.