Covariant Return Types in Method Overriding
Overriding methods in Java can differ in their return types, provided certain conditions are met. Specifically, Java supports covariant return types, allowing an overriding method to have a more specific return type than the method it overrides.
According to the Java Language Specification (JLS) section 8.4.5, this is permissible as long as the following rules are adhered to:
If the original method returns a reference type:
For example, consider the following code:
class ShapeBuilder { ... public Shape build() { .... } } class CircleBuilder extends ShapeBuilder{ ... @Override public Circle build() { .... } }
In this example, the build() method in CircleBuilder overrides the build() method in the ShapeBuilder. The return type of the overridden method is Shape, while the return type of the overriding method is Circle, which is a subtype of Shape. This is permitted by Java's covariant return types rule.
The above is the detailed content of When Can Overriding Methods in Java Have Different Return Types?. For more information, please follow other related articles on the PHP Chinese website!