Reputation: 61
Undergraduate ug = new Undergraduate (“Sam”, 999, 1);
Person p = (Person) ug // Type casting
p.writeOutput();
Undergraduate
is the child class of Person
. Undergraduate's method writeOutput
overrides that in Person
. Why is the writeOutput
of the Undergraduate
invoked, though variable p
references the object of type Person
?
Upvotes: 1
Views: 93
Reputation: 72844
That's what polymorphism is. From the official tutorials:
The Java virtual machine (JVM) calls the appropriate method for the object that is referred to in each variable. It does not call the method that is defined by the variable's type. This behavior is referred to as virtual method invocation and demonstrates an aspect of the important polymorphism features in the Java language.
Upvotes: 8
Reputation: 2073
Java is nice there and invokes undergraduate.writeoutput. You can not invoke persons method except from undergraduate via super.
Upvotes: 0