gpt4 book ai didi

java - 如何在对现有类进行本地继承的同时实现接口(interface)

转载 作者:行者123 更新时间:2023-11-30 03:20:14 31 4
gpt4 key购买 nike

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

public void randomMethod() {

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

这可能吗?是的,如何实现呢?

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

最佳答案

如果您想使用匿名内部类来执行此操作,则需要修改您的 Updatable 接口(interface),如下所示:

interface Updatable<T> {
public void update();
public void setComponent(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();

可更新的 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();

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

关于java - 如何在对现有类进行本地继承的同时实现接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31489046/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com