Reputation: 805
I have two classes ModalWinodw and SkinnableWindow both are extending Window class. I want to create class that has function from both classes, but in Java class can extends just one superclass. So how to solve this?
Upvotes: 0
Views: 2337
Reputation:
Composition (at least one, possibly both, of the "base" classes would be a member object). And lots of proxies as needed (some editors will help you here).
Yahoo Java OO!
Edit: While composition is "the way to go" here (without redesigning the class hierarchy), there are some specific limitations with it depending upon how interfaces and nominative names are used. If you need to pass the "specific" type (ModalWindow or SkinnableWindow) anywhere you're pretty much in a world of hurt as your new class can have at most one of them as an ancestor (so if it's one or less, you may be able to slip by). Using interfaces and being as general about types as possible can reduce this hurt.
Happy coding.
Upvotes: 2
Reputation: 245389
This is a case where the phrase "Composition over Inheritence" actually fits...
I would create an interface that combines the functionality of both classes that I want to fit.
I would then create a class that implements my new interface. That class would contain an instance of both ModalWindow and SkinnableWindow. Depending on what functionality is called, my class would simply pass the method call on to the appropriate class, leverage each class' functionality when needed.
Upvotes: 3
Reputation: 3905
You could use composition. Have your class have one (or both) as fields and expose their methods as pass-through methods.
Upvotes: 1