简体   繁体   中英

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);
        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.

是的,使用代理而不是扩展

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM