Home >Java >javaTutorial >Can Overridden Methods in Java Have Different Return Types?
Overriding Methods and Return Type Variance
Can overridden methods differ in return type?
Java's support for covariant return types allows overridden methods to possess more specific return types than the methods they override.
The overriding method's return type must be assignable to the return type of the overridden method. For instance:
class ShapeBuilder { ... public Shape build() { .... } class CircleBuilder extends ShapeBuilder{ ... @Override public Circle build() { .... }
As per the Java Language Specification (section 8.4.5), return type substitutability is allowed if:
Legacy Behavior (Java 5 and Before)
Prior to Java 5, overridden methods had invariant return types, meaning they needed to match the return type of the overridden method exactly.
The above is the detailed content of Can Overridden Methods in Java Have Different Return Types?. For more information, please follow other related articles on the PHP Chinese website!