Home > Java > javaTutorial > Can Overridden Methods in Java Have Different Return Types?

Can Overridden Methods in Java Have Different Return Types?

Mary-Kate Olsen
Release: 2024-11-30 13:12:11
Original
484 people have browsed it

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() {
    ....
}
Copy after login

As per the Java Language Specification (section 8.4.5), return type substitutability is allowed if:

  • The return types are reference types, with R1 (overridden method's return type) being either a subtype of R2 (overriding method's return type) or convertible to a subtype via unchecked conversion.
  • R1 is the erasure of R2 (removing type parameters).

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template