在Java中,如果返回类型分别是基元及其包装类,是否可以重写方法? [英] In Java, is it possible to override methods if return types are respectively a primitive and its wrapper class?
问题描述
在使用Java中重写和重写方法的想法时,我注意到这些方法的返回类型有一些灵活性。
While working with the idea of overriding and overridden methods in Java I have noticed that there is some flexiblity given for the return types of such methods.
这是一个一点理论:
派生类中重写方法的返回类型可以是相同的,或者是基类中重写方法的返回类型的子类。这种重写方法的返回类型是称为协变返回类型。
Here is a bit of theory: "The return type of an overriding method in the derived class can be the same, or a subclass of the return type of the overridden method in the base class. The return type of such an overriding method is known as a covariant return type."
以下示例假设B扩展A。
Example below supposes that B extends A.
Method in A:
public Object some_method() {....}
Method in B:
public Integer some_method() {....}
因此,我们看到B中的some_method()会覆盖A中的some_method(),因为Integer是Object的子类。
So, we see that some_method() in B overrides some_method() in A since Integer is a subclass of Object.
我想知道是否存在以下灵活性,以及由于自动装箱和取消装箱,以下是否会正常工作:
I wonder whether the following flexibility exists and whether the following will correctly work because of auto-boxing and unboxing:
Method in A:
public Integer some_method() {....}
Method in B:
public int some_method() {....}
OR
Method in A:
public int some_method() {....}
Method in B:
public Integer some_method() {....}
推荐答案
您只能返回父类返回类型的相同类型或子类及其称为Co-Variant返回类型。
You can only return same type or a sub-class of the parent's return type and its known as Co-Variant return types.
编译器允许您在原语和包装器之间自动装箱和取消装箱,但这不会使另一个成为另一个子类。基元不是类,不能以你的方式使用。
The compiler lets you auto-box and unbox between primitives and wrappers but this doesn't make one a sub-class of the other. Primitives are not classes and cannot be used in the way you have.
这篇关于在Java中,如果返回类型分别是基元及其包装类,是否可以重写方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!