首页 > 解决方案 > 如何从具有非常相似逻辑的子类中提取父类?

问题描述

我正在尝试创建几个最终可以添加到 JToolBar 的自定义按钮。我有一个从 JButton 扩展的类,如下所示:

public class CustomToolbarJButton extends JButton {
    public void setCustomProperties() {
        this.putClientProperty("Property1", "Value1");
    }

    // Some other CustomToolbarJButton specific code here.
}

我有另一个类,CustomToolbarJToggleButton,它从 JToggleButton 扩展而来,并具有与 setCustomProperties() 方法完全相同的代码。

我的问题是,有什么方法可以创建一个抽象父类,这两个类最终可以继承自,以便我可以将 setCustomProperties() 方法拉到该父类。

编辑

我想为我最终想要做的事情添加一些背景信息。

我想有一个这样的父类:

public abstract class CustomToolbarButton extends <some-class> {
    public void setCustomProperties() {
        this.putClientProperty("Property1", "Value1");
    }
}

public class CustomToolbarJButton extends CustomToolbarButton {
    // Some other CustomToolbarJButton specific code here.
}

public class CustomToolbarJToggleButton extends CustomToolbarButton {
    // Some other CustomToolbarJToggleButton specific code here.
}

并最终将按钮添加到工具栏,我想创建一个方法,如:

public void addCustomButtonToToolbar(boolean standardButtonOrToggleButton, String text) {
    CustomToolbarButton customToolbarButton = standardButtonOrToggleButton ? new CustomToolbarJButton(text) : new CustomToolbarJToggleButton(text);
    customToolbarButton.setCustomProperties();
    this.toolbar.add(customToolbarButton);  // toolbar is a JToolBar. I wanted to add the customToolbarButton directly to it, just like a standard JComponent.
}

这样的事情可能吗?

标签: javainheritance

解决方案


是的,您可以使用 来做到这一点interface,这与 like this 非常相似abstract class,但只有方法,没有字段:

public interface CustomProperties {
    public void setCustomProperties();
}

和:

public class CustomToolbarJButton extends JButton implements CustomProperties {
    public void setCustomProperties() {
        this.putClientProperty("Property1", "Value1");
    }

    // Some other CustomToolbarJButton specific code here.
}

注意implements关键字,您可以同时从多个接口继承..

正如我认为您可能需要的那样,您可以使用子类创建 CustomProperties 类型的对象。

CustomProperties obj = (CustomProperties) new CustomToolbarJButton();

我希望它有帮助:)

编辑:这可能会有所帮助,可能你有不同的要求..

public interface CustomProperties {
    public void setCustomProperties() {
        this.putClientProperty("Property1", "Value1");
    }
}

.

public class CustomToolbarJButton extends JButton implements CustomProperties {
    // Some other CustomToolbarJButton specific code here.
}

.

public class CustomToolbarJToggleButton extends JToggleButton implements CustomProperties {
    // Some other CustomToolbarJToggleButton specific code here.
}

这:编辑:

public void addCustomButtonToToolbar(boolean standardButtonOrToggleButton, String text) {
    CustomProperties customToolbarButton = standardButtonOrToggleButton ? new CustomToolbarJButton(text) : new CustomToolbarJToggleButton(text);
    customToolbarButton.setCustomProperties();
    this.toolbar.add((Component) customToolbarButton);
}

推荐阅读