Overridden methods in Java have the flexibility to vary in return types, following the principle of covariant return types. This means an overriding method can return a more specific data type than the one declared in the overridden method.
To illustrate, consider the following example:
class ShapeBuilder { ... public Shape build() { .... } } class CircleBuilder extends ShapeBuilder{ ... @Override public Circle build() { .... } }
In this scenario, although ShapeBuilder's build() method returns a Shape object, CircleBuilder's overriding build() method returns a Circle object, which is a more specialized type that extends Shape. This is permissible because Circle is assignable to Shape.
Covariant return types adhere to section 8.4.5 of the Java Language Specification, which outlines the following rules:
For reference types:
Prior to Java 5, Java enforced invariant return types, requiring the return type of overridden methods to precisely match the overridden method.
The above is the detailed content of Can Java Overridden Methods Have Different Return Types?. For more information, please follow other related articles on the PHP Chinese website!