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

Can Java Overridden Methods Have Different Return Types?

Linda Hamilton
Release: 2024-12-13 10:39:12
Original
282 people have browsed it

Can Java Overridden Methods Have Different Return Types?

Can Overridden Methods Have Different Return Types?

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

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:

  1. Void methods may be overridden only by void methods.
  2. Primitive return types must remain the same in overridden methods.
  3. For reference types:

    • The return type of the overriding method can be a subtype of the overridden method's return type.
    • The return type can be assignable to the overridden method's return type via unchecked conversion.
    • The return types can be erased to the same type.

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!

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