Java – if the return type of the rewriting method is original (such as double), can we change the return type of the rewriting method (such as int, char)?
•
Java
As follows:
Method to override:
double add (int a,int b){ }
Method of covering the above method:
int add(int a,int b){ }
Solution
It is impossible to use primitive types, but JDK 1.5 adds a function called covariant return types Therefore, with this function, a subclass can return a more specific type than the type declared by the parent class
The following code compiles well in JDK 1.7
public static class A { Number go() { return 0; }; } public static class B extends A { @Override Integer go() { return 0; } }
See JLS example 8.4 8.3-1. Covariant Return Types
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
二维码