This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Hi Friends, this is a code snippet which creates an instance of subclass and get it referred to superclass.why the superclass reference refer to the variable in superclass while it invokes method of subclass?
the phenomeon is call "overriding" a method. if you have a C++ background you should take note that every method is implicitly declare "virtual" except if they are declared final but then nobody can override it.
What you are experiencing is called "polymorphism". In programming languages it's the ability to process objects differently depending on their actual class regardless of the reference object.
When you create a class hiearchy, you can refer to any object in the heiarchy with a reference of any object higher in the heiarchy. When you then use any of the methods or public fields defined in the reference class, the runtime environment begins searching for the method or field in the actual class. If the method or field is not found in the actual class, the environment then moves up the hiearchy one level and checks the parent class for the item. It continues to do this until the method or field is found in one of the ancestor classes and it then uses that item.
This has the effect of always choosing the most specialized version of the method or field available. For example, given a base class shape, polymorphism enables the programmer to define different area methods for any number of derived classes, such as circles, rectangles and triangles. No matter what shape an object is, applying the area method to it will return the correct results.
Cheers, [ September 21, 2005: Message edited by: Tom Blough ]
Tom Blough<br /> <blockquote><font size="1" face="Verdana, Arial">quote:</font><hr>Cum catapultae proscriptae erunt tum soli proscripti catapultas habebunt.<hr></blockquote>