I ran at the following dilemma: there’s no multiple inheritance in Java but I need it, how to avoid it?
Below is the reason why I started thinking about it.
I was in need of a text box that has several specific properties and behavior (on focus and on blur events are handled). I developed DecoratedTextBox without hesitation:
public class DecoratedTextBox extends TextBox implements FocusHandler, BlurHandler {
public void onBlur(BlurEvent event) {
//cool feature implementation
}
public void onFocus(FocusEvent event) {
//another cool feature
}
//other cool features
}
My GUI started looking good, but I didn’t take into account PasswordTextBox. It also must have the same properties and behaviour that DecoratedTextBox has. But PasswordTextBox is inhereted from TextBox and it is in fact another class hierarchy branch. At once I remembered that it would be great if TextArea also has all those cool properties and behavior etc.
So what is wrong with my design that it leads to thoughts about multiple-inheritance? What must be done to satisfy mentioned requirements?
Some clarification
As a result I had to inherit from PasswordTextBox, TextArea and so on to take advantage of their features (these classes are from GWT library). But I cannot understand how to weave composition here.
Update
Correct me If I understood what Anders Johansen said in a wrong way.
The solution should look like this:
public class DecoratedTextBox extend AbstractEventHandler {
private TextBox textBox;
//wrap TextBox methods
public String getText() {
return textBox.getText();
}
}
public class DecoratedPasswordTextBox extend AbstractEventHandler {
private PasswordTextBox passwordTextBox;
//wrap TextBox methods
//...
}
public class DecoratedTextArea extend AbstractEventHandler {
private TextAre textArea;
//wrap TextBox methods
//...
}
public abstract class AbstractEventHandler implements FocusHandler, BlurHandler {
public void onBlur(BlurEvent event) {
//default cool feature implementation
}
public void onFocus(FocusEvent event) {
//another default cool feature implementation
}
}
updated
I tried variants suggested by Anders Johansen and Hilbrand Bouwkamp, but in each case I ran at a problem that I have a method (its signature cannot be changed) that adds widgets and one of the args is Widget itself. So if I’m not subclassing from something that is a subclass of Widget, I break a lot of classes.
Still continue thinking on solution.
I can’t guesss what kind of cool features you like to add, but what about making a TextBoxBaseDecorator class, which looks something like:
}
You could create subclasses that create wrappers for the specific widgets, like TextBox, PasswordTextBox and TextArea.