简体   繁体   English

隐藏超类的方法

[英]Hiding methods of superclass

I've read the Overriding and Hiding Methods tutorial. 我已经阅读了Overriding and Hiding Methods教程。 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. 我不喜欢这个设计的是append仍然是子类的可见方法。 Instead of throwing the UnsupportedOperationException , I could have left the body empty. 我可以将身体留空,而不是抛出UnsupportedOperationException 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 . 这是Joshua Bloch在Effective Java,Second Edition中的推荐

Item 16: Favor composition over inheritance 第16项:赞成组合而不是继承

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. 这是一个OOP问题/功能。 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. 你的类仍然是一个JTextArea,因此它可以被不知道你的子类的代码使用,它将它视为JTextArea,期望JTextArea中的所有方法都在那里并正常工作。

If you need to define a new interface, you should define a new class not extending JTextArea but instead encapsulating it. 如果需要定义新接口,则应定义一个不扩展JTextArea的新类,而是封装它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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