I have an interface called A:
public interface A {
void X(T t);
}
I then have two subclasses (B and C) that implement this interface, but each of them pass a different type to X lets say B passes type foo and C passes type bar:
public class B implements A {
@Override
public <T extends foo> void X(T type1)
}
public class C implements A {
@Override
public <T extends bar> void X(T type2)
}
What am I doing wrong and why doesn't this work? The compiler keeps telling me that "Method does not override method from its superclass".
Thanks in advance!
You can make the methods default in the interface itself, Default methods are introduced in interfaces since Java8 and if you have default methods in an interface it is not mandatory to override them in the implementing class.
The @Override annotation indicates that the child class method is over-writing its base class method. It extracts a warning from the compiler if the annotated method doesn't actually override anything. It can improve the readability of the source code.
Yes, an overridden method can have a different access modifier but it cannot lower the access scope. Methods declared public in a superclass also must be public in all subclasses. Methods declared protected in a superclass must either be protected or public in subclasses; they cannot be private.
Instance methods can be overridden only if they are inherited by the subclass. A method declared final cannot be overridden. A method declared static cannot be overridden but can be re-declared. If a method cannot be inherited, then it cannot be overridden.
Even with generic methods, when they are overridden, the generics must match exactly.
One way that might not meet your requirements is to remove the upper bounds on the implementing class, e.g.
class B implements A {
@Override
<T> void X(T type1) { /* impl */ }
}
But if you need the upper bound, then represent the upper bound with a type parameter on the interface.
interface A<U> {
<T extends U> void X(T t);
}
Then you can supply the type argument for the upper bound in the implementing classes.
class B implements A<Foo> {
@Override
public <T extends Foo> void X(T type1) { /* impl */ }
}
class C implements A<Bar> {
@Override
public <T extends Bar> void X(T type2) { /* impl */ }
}
But because anything you can call on T
you can also call on Foo
or Bar
, maybe the methods don't need to be generic.
interface A<T> {
void X(T t);
}
class B implements A<Foo> {
@Override
public void X(Foo type1) { /* impl */ }
}
class C implements A<Bar> {
@Override
public void X(Bar type2) { /* impl */ }
}
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