Java 如何在执行现有类的本地继承时实现接口

Java 如何在执行现有类的本地继承时实现接口,java,interface,polymorphism,overriding,Java,Interface,Polymorphism,Overriding,我需要从稍微修改过的类(例如,从JButton)创建一个对象。此修改包括添加简单方法和实现附加接口,如下所示: public void randomMethod() { JButton button = new JButton() implements updatable{ public void update() {} }; } 有可能吗?是的,如何实施 我不想为它创建单独的类,特别是当我有一堆要修改的类,并且我不经常使用它们的对象时。使用一个抽象类,将更新

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

public void randomMethod() {

    JButton button = new JButton() implements updatable{ 
     public void update() {} 
    };
} 
有可能吗?是的,如何实施


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

使用一个抽象类,将
更新作为一个接口来实现:

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

    public void update();
}
可更新接口:

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

    public void update();
}
现在,您可以使用省略了
update
实现的抽象类:

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

如果要使用匿名内部类执行此操作,则需要修改
可更新的
接口,如下所示:

interface Updatable<T> {
    public void update();
    public void setComponent(T t);
}
接口可更新{
公共无效更新();
公共空间组件(T);
}
然后,您可以轻松地为不同的组件创建匿名内部类

可更新的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();
updateable-updateablebutton=new-updateable(){
私人按钮;
公共无效设置组件(JButton JButton){
this.jButton=jButton;
}
公共无效更新(){
setText(“someText”);
}   
};
setComponent(新的JButton());
updateButton.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();
updateablejlabel=newupdateable(){
私人JLabel JLabel;
公共无效设置组件(JLabel jButton){
this.jLabel=jButton;
}
公共无效更新(){
jLabel.setText(“someText”);
}   
};
可更新的JLabel.setComponent(新的JLabel());
updateablejlabel.update();

你不必再创建一个你想要的新类。

我不想为它创建单独的类,我想他不想为每个类创建单独的类,但一个为所有类都可以。我真的不理解你的评论。你能详细说明一下吗?为什么不创建一个单独的类呢?分开上课是好的。事实上,您已经在创建一个类,尽管是一个匿名的内部类。@CKing的想法是,他不想为每个按钮创建一个单独的类,因为将会有很多按钮。但在本例中,您只创建一个父类,所有按钮仍然只是具有特定实现的匿名类。请阅读:。我对您的问题的解释是,您不想显式创建一个扩展JButton并实现可更新的类。这个解释正确吗?看看我的答案,它展示了如何消除创建扩展JButton并实现可更新的新类的需要