[英]Overriding Function in Polymorphism with different return type
Take a look into following code and help me understanding why the return type of "mf.display" is Object Type. 查看以下代码,帮助我理解为什么“ mf.display”的返回类型为“对象类型”。 Though "mf" is of "MyFather" type but still return type of "mf.display()" must be Integer type
尽管“ mf”是“ MyFather”类型,但返回类型“ mf.display()”必须是整数类型
class MyFather
{
Object display()
{
System.out.println(1000);
return 1000;
}
}
class MySon extends MyFather
{
@Override
Integer display()
{
System.out.println(500);
return 500;
}
}
public class TestInheritance {
public static void main(String[] args) {
MyFather mf = new MySon();
Integer myInt = mf.display(); // Error.Type mismatch cannot convert from Object to
// Integer
}
}
The type myFather
declares a method Object display()
, so when you write 类型
myFather
声明一个方法Object display()
,因此在编写时
mf.display()
the type of that expression is Object
. 该表达式的类型为
Object
。 It doesn't matter what type of object you assigned to mf
. 分配给
mf
的对象类型无关紧要。 This makes sense because mf
could also have been a method parameter: 这是有道理的,因为
mf
也可以是方法参数:
static void useFather(myFather mf) {
mf.display();
}
and you could call such a method with any instance, such as 您可以使用任何实例调用此类方法,例如
useFather(new myFather());
The code must not be allowed to assume it has an instance of the subclass. 不允许代码假定它具有子类的实例。
For clarity of discussion I should state that , mySon class (which should be named MySon) is overriding the display() of myFather class (Again should be named MyFather) because as per the Java norms , for overriding a method 为了便于讨论,我应该指出,mySon类(应命名为MySon)将覆盖myFather类的display()(再次应命名为MyFather),因为按照Java规范,用于覆盖方法
The return type must be the same as, or a subtype of, the return type declared
in the original overridden method in the superclass
Now having stated that lets continue on our discussion , 现在已经说了让我们继续讨论,
The only way to access an object is through a reference variable, and there are a few key things to remember about references. 访问对象的唯一方法是通过引用变量,关于引用要记住一些关键的事情。
I think you should refer some standard Java book on this subject if you want to learn more about overriding and overloading. 如果您想了解有关重写和重载的更多信息,我认为您应该参考有关此主题的一些标准Java书籍。
Cheers! 干杯!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.