隐藏超类的方法
我已阅读重写和隐藏方法教程。由此,我收集了以下信息:
如果子类定义了与子类具有相同签名的类方法 超类中的类方法,子类中的方法隐藏 超类中的一个。
因此,我做了以下事情:
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();
}
}
我不喜欢这种设计的是 append
仍然是子类的可见方法。我可以将正文留空,而不是抛出 UnsupportedOperationException
。但两人都觉得丑。
话虽如此,是否有更好的方法来隐藏超类的方法?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果可能的话,使用组合。这是 Joshua Bloch 在 Effective Java,第二版 中推荐的。
第 16 条:优先考虑组合而不是继承
例如:
Use composition, if possible. This is recommended by Joshua Bloch in Effective Java, Second Edition.
Item 16: Favor composition over inheritance
For example:
不,据我所知。
这是一个 OOP 问题/功能。您的类仍然是一个 JTextArea,因此它可以被不知道您的子类的代码使用,子类会将其视为 JTextArea,期望 JTextArea 中的所有方法都在那里并正常工作。
如果您需要定义一个新接口,您应该定义一个新类,而不是扩展 JTextArea 而是封装它。
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.
是的,使用委托而不是扩展。
Yes, use a delegate rather than extending.