0

I have the following situation:

I need my class let's say A to extend JComponent and a different class let's say B.

Now, I know that multiple inheritance is not possible in java, and that a proper way to do this would be to implement BInterface which will give me access to all methods from B.

The issue is that class B contains ~15 methods, and inside A I only need to override 2 of them, and all the other ones to use the 'super' implementation.

Question is: is there a possible way to do this without having to implement inside A all the methods from B?

Note: I'm not trying to add too much complexity to my code, if the 'workaround' for this problem breaks oop programming principles then I should better redesign my code.

3
  • you could add default implementation to the interface methods so you don't have to implement all of them in the A class. Commented May 7, 2020 at 17:30
  • Have a look at baeldung.com/java-static-default-methods Commented May 7, 2020 at 17:31
  • If A only needs 2 members out of B, those two members should probably exist in their own type, so clients won't have to rely on the entirety of B just to access the few dependencies they need. Segregate the interface. Commented May 7, 2020 at 18:00

2 Answers 2

2

As you said multiple inheritance is not supported in java. But in general its a good practice to use composition instead of inheritance [Effective Java - item 18]. Read about it here

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

1 Comment

0

You can use default implementation of java 8 feature.

  1. Create an interface named as ABinterface. provide all 13 methods as default means having definition and declare 2 methods (like abstract methods).

  2. Class A and B will implement ABinterface and override those 2 methods according to their need.

  3. Class A which will extend jsComponent and implement ABInterface can access all other existing 13 methods also.

    You haven't provided the enough information in this query. So you need to think according to real word scenarios with oops concepts before implementing this.

    You can also use composition instead of inheritance.

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.