user4147874
user4147874

Reputation: 61

Why is the subclass method definition used?

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

Answers (2)

M A
M A

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

thi gg
thi gg

Reputation: 2073

Java is nice there and invokes undergraduate.writeoutput. You can not invoke persons method except from undergraduate via super.

Upvotes: 0

Related Questions