I've read the Overriding and Hiding Methods tutorial. And from that, I gathered the following:
If a subclass defines a class method with the same signature as a class method in the superclass, the method in the subclass hides the one in the superclass.
As such, I did the following:
import javax.swing.JTextArea;
public final class JWrappedLabel extends JTextArea{
private static final long serialVersionUID = -844167470113830283L;
public JWrappedLabel(final String text){
super(text);
setOpaque(false);
setEditable(false);
setLineWrap(true);
setWrapStyleWord(true);
}
@Override
public void append(final String s){
throw new UnsupportedOperationException();
}
}
What I don't like about this design is that append
is still a visible method of the subclass. Instead of throwing the UnsupportedOperationException
, I could have left the body empty. But both feel ugly.
That being said, is there a better approach to hiding methods of the superclass?
Static Methods If a subclass defines a static method with the same signature as a static method in the superclass, then the method in the subclass hides the one in the superclass.
When super class and sub class contains same method including parameters and if they are static. The method in the super class will be hidden by the one that is in the sub class. This mechanism is known as method hiding.
The superclass method is used to access the parent class inside a child class. This method has a variety of uses when inheriting parent members.
In method overriding, when base class reference variable pointing to the object of the derived class, then it will call the overridden method in the derived class. In the method hiding, when base class reference variable pointing to the object of the derived class, then it will call the hidden method in the base class.
Use composition, if possible. This is recommended by Joshua Bloch in Effective Java, Second Edition.
Item 16: Favor composition over inheritance
For example:
import javax.swing.JTextArea;
public final class JWrappedLabel {
private static final long serialVersionUID = -844167470113830283L;
private final JTextArea textArea;
public JWrappedLabel(final String text){
textArea = new JTextArea(text);
textArea.setOpaque(false);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
}
//add methods which delegate calls to the textArea
}
Nope that I know of.
It is a OOP problem/feature. You class still IS a JTextArea, and as such it could be used by code unaware of you subclass which would treat it as a JTextArea, expecting all of the method in JTextArea to be there and work properly.
If you need to define a new interface, you should define a new class not extending JTextArea but instead encapsulating it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With