Take a look into following code and help me understanding why the return type of "mf.display" is Object Type. Though "mf" is of "MyFather" type but still return type of "mf.display()" must be Integer type
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
mf.display()
the type of that expression is Object
. It doesn't matter what type of object you assigned to mf
. This makes sense because mf
could also have been a method parameter:
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
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.
Cheers!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.