java – 不能包含与不同参数相同的界面?
发布时间:2020-11-17 13:15:26 所属栏目:Java 来源:互联网
导读:请考虑以下示例: public class Sandbox { public interface ListenerT extends JComponent { public void onEvent(T event); } public interface AnotherInterface extends ListenerJPanel, Liste
|
请考虑以下示例: public class Sandbox {
public interface Listener<T extends JComponent> {
public void onEvent(T event);
}
public interface AnotherInterface extends Listener<JPanel>,Listener<JLabel> {
}
}
这将失败,并显示以下错误 /media/PQ-WDFILES/programming/Sandbox/src/Sandbox.java:20: Sandbox.Listener cannot be inherited with different arguments: <javax.swing.JPanel> and <javax.swing.JLabel>
public interface AnotherInterface extends Listener<JPanel>,Listener<JLabel> {
^
1 error
为什么呢生成的方法没有重叠.事实上,这基本上是指的 public interface AnotherInterface {
public void onEvent(JPanel event);
public void onEvent(JLabel event);
}
没有重叠.那为什么会失败呢? 如果你想知道我在做什么,并且有一个更好的解决方案:我有一堆事件和一个监听器接口,几乎完全像上面的监听器类.我想要创建一个适配器和适配器接口,为此我需要扩展所有的监听器接口与一个特定的事件.这可能吗?有没有更好的方法来做到这一点? 解决方法不,你不行这是因为泛型仅在编译器级才支持.所以你不能这样想 public interface AnotherInterface {
public void onEvent(List<JPanel> event);
public void onEvent(List<JLabel> event);
}
或实现与几个参数的接口. UPD 我认为解决方法将是这样的: public class Sandbox {
// ....
public final class JPanelEventHandler implements Listener<JPanel> {
AnotherInterface target;
JPanelEventHandler(AnotherInterface target){this.target = target;}
public final void onEvent(JPanel event){
target.onEvent(event);
}
}
///same with JLabel
} (编辑:哈尔滨站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
