Java – override methods and then face problems
•
Java
When the overlay method then faces a problem:
public interface IProduct { public void sendMessage(Object object); } @Service public class ProductManagere implements IProduct{ @Override public void sendMessage(Product product) { // Added logic } }
But below the exception:
I don't understand why this exception is thrown I want product to be a subtype of object, so it won't throw an exception
Solution
In Java, overriding the covariance of parameters is not allowed
Therefore, you must keep object as a parameter in a subclass (which may not be what you want) or make the interface a general interface, for example:
public interface IProduct<T> { void sendMessage(T object); }
And subclasses:
@Service public class ProductManagere implements IProduct<Product>{ @Override public void sendMessage(Product product) { // Added logic } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码