java - Overriding Function in Polymorphism with different return type -
take following code , me understanding why return type of "mf.display" object type. though "mf" of "myfather" type still return type of "mf.display()" must 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 object // integer } }
the type myfather
declares method object display()
, when write
mf.display()
the type of expression object
. doesn't matter type of object assigned mf
. makes sense because mf
have been method parameter:
static void usefather(myfather mf) { mf.display(); }
and call such method instance, such as
usefather(new myfather());
the code must not allowed assume has instance of subclass.
Comments
Post a Comment