如何在对现有的本地继承的同时实现接口 class

How to implement an interface while doing local inheritance of existing class

我需要从稍微修改过的 class(例如从 JButton)创建一个对象。此修改包括添加简单方法和实现附加接口,如下所示:

public void randomMethod() {

    JButton button = new JButton() implements updatable{ 
     public void update() {} 
    };
} 

这可能吗?是的,如何实施?

我不想为它创建单独的 class,尤其是当我有一堆要修改并且我不经常使用它们的对象时。

使用抽象 class 将 update 作为接口实现:

import javax.swing.JButton;
public abstract class UpdateableJButton extends JButton implements Updateable {
    // ...
}

可更新界面:

public interface Updateable {

    public void update();
}

现在您可以使用抽象 class,其中省略了 update 实现:

UpdateableJButton button = new UpdateableJButton() {
    @Override
    public void update() {
        // add specific implementation
    }
};

如果您想使用匿名内部 classes 执行此操作,您需要按如下方式修改您的 Updatable 接口:

interface Updatable<T> {
    public void update();
    public void setComponent(T t);
}

然后您可以轻松地为不同的组件创建匿名内部 classes。

可更新的 JButton

Updatable<JButton> updatableButton = new Updatable<JButton>() {
        private JButton jButton;

        public void setComponent(JButton jButton) {
            this.jButton = jButton;
        }

        public void update() {
            jButton.setText("someText");
        }   
    };

    updatableButton.setComponent(new JButton());
    updatableButton.update();

可更新的 JLabel

Updatable<JLabel> updatableJLabel = new Updatable<JLabel>() {
        private JLabel jLabel;

        public void setComponent(JLabel jButton) {
            this.jLabel = jButton;
        }

        public void update() {
            jLabel.setText("someText");
        }   
    };

    updatableJLabel.setComponent(new JLabel());
    updatableJLabel.update();

您不再需要创建您想要的新 class。