While overriding method then facing an issue:
public interface IProduct {
public void sendMessage(Object object);
}
@Service
public class ProductManagere implements IProduct{
@Override
public void sendMessage(Product product) {
// Added logic
}
}
But getting below exception:
The method sendMessage(Product) of type ProductManagere must override or implement a supertype method
I don't understand why is throwing this exception. I expect product is the subtype of Object so it will not throw an exception.
In Java, overriding doesn't allow the covariance of the parameter.
It is only possible for the return type.
Why ?
Because changing the type of the parameter of the method in the subclass is not designed to override a method but to overload it. And it is not your intention.
So either you have to keep Object as parameter in the subclass (probably not what you want to) or make the interface a generic interface such as :
public interface IProduct<T> {
void sendMessage(T object);
}
And the subclass :
@Service
public class ProductManagere implements IProduct<Product>{
@Override
public void sendMessage(Product product) {
// Added logic
}
}
This is not allowed in Java. You have to use generics.
public interface IProduct<T> {
public void sendMessage(T object);
}
And the service:
@Service
public class ProductManagere implements IProduct<Product> {
@Override
public void sendMessage(Product product) {
// Added logic
}
}
Alternatively, change the method in the interface to match the Product.
public void sendMessage(Product object);
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