How to create a class that “extends” two existing

2019-01-26 20:40发布

I very well know that it can be done with the help of interfaces and i have done it many times. But this time my situation is quite difference. I have class A , class B and i need to create another class C which extends both A and B because C should have boths functionality and also note that A and B are not inter related so even i cant say A may extend class B.

I am quite confused what should i do right now. I know we cant change java... but at least there would be some way possible. Even the nearest may also do... please help me out.

Adding more details:- Class B is a standard API while class A is a common exception class that need to be inherited by all exception classes.

Related question:

8条回答
乱世女痞
2楼-- · 2019-01-26 21:19

http://en.wikipedia.org/wiki/Adapter_pattern

Your problem is solved by the adapter pattern. I went back to check the wiki document, just to be sure :)

查看更多
一夜七次
3楼-- · 2019-01-26 21:23

It is not possible to extend two classes, and thus inherit functionality from both, in Java. Your easiest alternative it to "wrap" at least one of the two classes. So, instead of also extending B you can have an instance of B inside C, and declare each of B's methods on C, and pass them through. C would not "be" a B, but it sounds like you just want to inherit functionality. And if that's true of A too, then, well, you should be using this pattern for both A and B and not extending either.

查看更多
小情绪 Triste *
4楼-- · 2019-01-26 21:23

Maybe you can create a new class D, and have both class A and class B inherit from D?

查看更多
Juvenile、少年°
5楼-- · 2019-01-26 21:24

Change the way you are thinking. Think in interfaces. It means that class A is actually an implementation of interface A' and class B is an implementation of interface B'. And you actually want a class C that implements both interfaces A' and B'. Class C doesn't need to extend anything or to use any particular pattern or whatsoever. It can extend A and delegate some methods to B, or it can extend B and delegate some methods to A. Or it can delegate all methods to A and B - implementation is your decision.

查看更多
劳资没心,怎么记你
6楼-- · 2019-01-26 21:25

Make use of composition. Class C will contain an instance each of classes A and B.

查看更多
兄弟一词,经得起流年.
7楼-- · 2019-01-26 21:26

You may try create class C that will contain one instance of class A and one of class B and their methods (create methods with same names that will just call methods from A and B), it's called Composition - another method in opposite to inheritance. Of course that's in case if you don't need instanceof to work with that C class.

查看更多
登录 后发表回答