Consider the following example:
public class Sandbox {
public interface Listener<T extends JComponent> {
public void onEvent(T event);
}
public interface AnotherInterface extends Listener<JPanel>, Listener<JLabel> {
}
}
This fails with the following error
/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
Why though? There is no overlap in the generated methods. As a matter of fact, that essentially means
public interface AnotherInterface {
public void onEvent(JPanel event);
public void onEvent(JLabel event);
}
No overlap there. So why is it failing?
In case your wondering what I'm doing and have a better solution: I have a bunch of Events and a Listener interface that's almost exactly like the Listener
class above. I'm wanting to create an adapter and an adapter interface, and for that I need to extend all the Listener interfaces with a specific event. Is this possible? Is there a better way to do this?
Yes, you can have overloaded methods (methods with the same name different parameters) in an interface.
You could use an interface method with a variable number of arguments using the params keyword. But you then need to cast each argument to the appropriate type, which is a bit error prone. Show activity on this post. Methods with different parameters cannot both implement the same interface method declaration.
A class can implement multiple interfaces and many classes can implement the same interface. A class can implement multiple interfaces and many classes can implement the same interface. Final method can't be overridden. Thus, an abstract function can't be final.
It is prohibited that a type implements or extends two different instantiations of the same interface. This is because the bridge method generation process cannot handle this situation.
No. You cant. It's because generics are supported only at compiler level. So you can't do thinks like
public interface AnotherInterface {
public void onEvent(List<JPanel> event);
public void onEvent(List<JLabel> event);
}
or implements interface with several parameters.
upd
I think workaround will be like this:
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With