隐藏超类的方法

mrk*_*rts 8 java swing method-hiding

我已经阅读了Overriding and Hiding Methods教程.从那以后,我收集了以下内容:

如果子类定义的类方法与超类中的类方法具有相同的签名,则子类中的方法会隐藏超类中的方法.

因此,我做了以下事情:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

我不喜欢这个设计的是它append仍然是子类的可见方法.UnsupportedOperationException我可以把身体留空,而不是扔掉它.但两人都觉得难看.

话虽如此,有没有更好的方法来隐藏超类的方法?

dog*_*ane 11

如果可能,使用合成.这是Joshua Bloch在Effective Java,Second Edition中的推荐.

第16项:赞成组合而不是继承

例如:

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
}
Run Code Online (Sandbox Code Playgroud)