How to avoid multiple inheritance?

For the project, I have the following classes:

  • Superclass
  • Subclass 1
  • Subclass 2

Two subclasses extend the superclass. Now I need a third class with EXACT behavior (reading, a similar implementation of overridden methods) of both SubClass 1 and Subclass 2. Since Subclass 1 overrides only one method in SuperClass, and Subclass 2 does not override this method, I want the third class to inherit Superclass and just implemented it using the methods of subclass 1 and subclass 2. Now is this a good OO design? I see no other solution, because multiple inheritance in Java is simply not possible. Are there any alternatives?

+4
source share
2

Java8 . . , , .

, . ; , .

: , / ; , . .

+8

Java 8, @GhostCat. OO . , , , .

public class Main {

    public static void main(String... args) {
        SuperClass sc = new SubClass3();
        sc.foo();  // overridden foo
        sc.bar();  // overridden bar
    }

    interface SuperClass {
        default void foo() {
            System.out.println("default foo");
        }
        default void bar() {
            System.out.println("default bar");
        }
    }

    interface SubClass1 extends SuperClass {
        @Override
        default void foo() {
            System.out.println("overridden foo");
        }
    }

    interface SubClass2 extends SuperClass {
        @Override
        default void bar() {
            System.out.println("overridden bar");
        }
    }

    static class SubClass3 implements SubClass1, SubClass2 {}
}
+3

Source: https://habr.com/ru/post/1650485/


All Articles