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

When Can Overriding Methods in Java Have Different Return Types?

Barbara Streisand
Release: 2024-12-02 19:03:14
Original
323 people have browsed it

When Can Overriding Methods in Java Have Different Return Types?

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 void, the overriding method must also return void.
  • If the original method returns a primitive type, the overriding method must return the same primitive type.
  • If the original method returns a reference type:

    • The overriding method's return type must be a subtype of the original method's return type.
    • Alternatively, the overriding method's return type can result from unchecked conversion of the original method's return type, or
    • The overriding method's return type can be the erasure of the original method's return type (after generic type parameters are removed).

For example, consider the following code:

class ShapeBuilder {
    ...
    public Shape build() {
        ....
    }
}

class CircleBuilder extends ShapeBuilder{
    ...
    @Override
    public Circle build() {
        ....
    }
}
Copy after login

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!

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