Polymorphism
ØA
reference can be polymorphic, which can be defined as
"having many forms"
obj.doIt();
ØThis
line of code might execute different methods at different
times if the object that
obj
points to changes
ØPolymorphic
references are resolved at run time; this is called
dynamic binding.
ØAn
object reference can refer to an object of its
class, or to an object of any class related to it by
inheritance
ØFor
example, if the
Holiday
class is used to derive a child class called
Christmas,
then a
Holiday
reference could be used to point to a
Christmas
object.
Holiday day;
day = new Christmas();
day.doIt(); //in the above code, day is a Christmas object..
****NOTE: For Polymorphism to work when
calling a method from the object which is a
child of the parent declared -> the called
method must exist in parent
MC Example:
What is valid? II Only - because subString and compareTo methods do not EXIST in Parent Class which is Object Class -- Object class has equals method so child equals method is called -> so equals method in String class. Code Example:
//main driver
//Nick class -
parent class //Donna class - child class
public class Donna
extends Nick
CODE COMPILES AND RUNS:
--If
you take out method doIt from parent Nick --
code does not compile! |