4

For a project, I have following classes:

  • SuperClass
  • Subclass 1
  • Subclass 2

The two subclasses extend the superclass. Now, I need a third class with the EXACT behaviour (read, same overriden method implementations) of both SubClass 1 and Subclass 2. Because Subclass 1 overrides only 1 method in SuperClass, and Subclass 2 doesn't override that method, I want to make the third class inherit Superclass and just implement it with the methods of Subclass 1 and Subclass 2. Now, is this good OO-design? I see no other solution because multiple inheritance in Java just isn't possible. Are there any alternatives?

2
  • 4
    Favour composition over inheritance... Commented Aug 7, 2016 at 22:14
  • 3
    It'd be useful to see the class definitions and how you'll use them to say whether it's good design Commented Aug 7, 2016 at 22:15

2 Answers 2

11

Java8 introduced default and static methods for interfaces. To a certain degree, that allows for multiple inheritance. But most likely, the correct solution would be to rework your design.

You see, inheritance is not about code re-use. It is about creating useful abstractions; and make good use of polymorphism for example.

In your case: maybe those functionalities could/should be put into smaller interfaces; and then segregated into their own, independent classes. And then you use composition of objects instead of inheritance to build the thing you need.

Sign up to request clarification or add additional context in comments.

Comments

4

Here is an example using Java 8's default methods as @GhostCat mentioned. I don't see anything wrong with this OO design per se. Whether or not it's appropriate to your use case depends on the details of the problem you're solving.

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 {}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.