开发者

Hiding methods of superclass

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);开发者_StackOverflow中文版
        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?


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.


Yes, use a delegate rather than extending.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜