I am attempting to override a method declaration within an interface that extends another interface. Both of these interfaces use generics. According to the Java tutorials, this should be possible, but the example does not use generics. When I try to implement it, the compiler shows the following error (I've replaced names because some of the code is not my own.):
myMethod(T) in InterfaceExtended clashes with myMethod(T) in Interface; both methods have the same erasure, but neither overrides the other.
Code looks like this:
public interface Interface<T>
{
public void myMethod(T x);
}
public interface ExtendedInterface<T> extends Interface<T>
{
public void myMethod(T x);
}
If anyone has suggestions as to how to alter this to make it acceptable, or an explanation regarding the reason this is causing a problem, I would very much appreciate it.
Thanks!
badPanda
No. Interface methods can be implemented. To overload/override a method, that method must be defined first. Interface do not contain method definition.
Extending InterfacesAn interface can extend another interface in the same way that a class can extend another class. The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface.
An interface can extend other interfaces, just as a class subclass or extend another class. However, whereas a class can extend only one other class, an interface can extend any number of interfaces.
Java does not support "multiple inheritance" (a class can only inherit from one superclass). However, it can be achieved with interfaces, because the class can implement multiple interfaces. Note: To implement multiple interfaces, separate them with a comma (see example below).
Do you want an overloaded version of myMethod? Then you should not use T twice, but like this:
public interface Interface<T>
{
public void myMethod(T x);
}
public interface ExtendedInterface<T, V> extends Interface<T>
{
public void myMethod(V x);
}
Now it is possible to have something like this:
class MyClass implements ExtendedInterface<String, Integer> {
public void myMethod(String x) { .. }
public void myMethod(Integer x) { .. }
}
Edit: interestingly enough, this also works (although it is useless):
class MyClass implements ExtendedInterface<String, String> {
public void myMethod(String x) { .. }
}
This does work. You could have a problem if your class implements twice the same interface with two different generics types.
For example :
class MyClass implements Interface<String>, ExtendedInteface<Integer>{
}
For example this code only fails on the third class.
And here is the message I have on IntelliJ X :
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