java – 不能包含与不同参数相同的界面?

前端之家收集整理的这篇文章主要介绍了java – 不能包含与不同参数相同的界面?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
请考虑以下示例:
  1. public class SandBox {
  2. public interface Listener<T extends JComponent> {
  3. public void onEvent(T event);
  4. }
  5.  
  6. public interface AnotherInterface extends Listener<JPanel>,Listener<JLabel> {
  7. }
  8. }

这将失败,并显示以下错误

  1. /media/PQ-WDFILES/programming/SandBox/src/SandBox.java:20: SandBox.Listener cannot be inherited with different arguments: <javax.swing.JPanel> and <javax.swing.JLabel>
  2. public interface AnotherInterface extends Listener<JPanel>,Listener<JLabel> {
  3. ^
  4. 1 error

为什么呢生成方法没有重叠.事实上,这基本上是指的

  1. public interface AnotherInterface {
  2. public void onEvent(JPanel event);
  3. public void onEvent(JLabel event);
  4. }

没有重叠.那为什么会失败呢?

如果你想知道我在做什么,并且有一个更好的解决方案:我有一堆事件和一个监听器接口,几乎完全像上面的监听器类.我想要创建一个适配器和适配器接口,为此我需要扩展所有的监听器接口与一个特定的事件.这可能吗?有没有更好的方法来做到这一点?

解决方法

不,你不行
这是因为泛型仅在编译器级才支持.所以你不能这样想
  1. public interface AnotherInterface {
  2. public void onEvent(List<JPanel> event);
  3. public void onEvent(List<JLabel> event);
  4. }

或实现与几个参数的接口.

UPD

我认为解决方法将是这样的:

  1. public class SandBox {
  2. // ....
  3. public final class JPanelEventHandler implements Listener<JPanel> {
  4. AnotherInterface target;
  5. JPanelEventHandler(AnotherInterface target){this.target = target;}
  6. public final void onEvent(JPanel event){
  7. target.onEvent(event);
  8. }
  9. }
  10. ///same with JLabel
  11. }

猜你在找的Java相关文章