Polymorphism via Inheritance
 

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
(otherwise, syntax error).
If called method exists in both parent and child -> child method called only.
If method exists in only parent (not child) -> code compiles and parent method is called.

MC Example:
Object obj = new String("This is a test!");

What is valid?

I. System.out.println(obj.substring(2,7));
II System.out.println(obj.equals("This is a test!"));
II System.out.println(obj.compareTo("This is a test!"));

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 n = new Donna();
n.doIt();

//Nick class - parent class
public class Nick {

    public Nick() {
           System.out.println("In Nick");
    }

    public void doIt() {
           System.out.println("Hi Nick");
    }
}

//Donna class - child class

public class Donna extends Nick
{

     public Donna () {
         System.out.println("In Donna");
     }

     public void doIt() {
         System.out.println("Hi Donna");
     }
}

CODE COMPILES AND RUNS:
In Nick //child constructor called first - but calls parent first
In Donna //child constructor
Hi Donna //child method

--If you take out method doIt from parent Nick -- code does not compile!
--If you take out method doIt from child Donna -- code compiles and calls parent doIt!
--Method in both Parent and Child -- code compiles and calls child doIt!