f()
defined in T.T v = new S();
v.f()
uses the definition from S rather than T.To understand the above points → We simulate this using Java Class Hierarchy.
Polymorphic reverse
public void reverse(Object[] objarr){
Object tempobj;
int len = objarr.length;
for(int i=0;i < n/2; i++){
tempobj = objarr[i];
objarr[i] = objarr[(n-1)-i];
objarr[(n-1)-i] = tempobj;
}
}
Polymorphic find
public int find(Object[] objarr, Object o){
int i;
for(i=0;i<objarr.length;i++){
if(objarr[i] == o) { return i; }
}
return (-1);
}
==
translates to Object.equals()
Polymorphic sort
public interface Comparable{
public abstract int cmp(Comparable s);
}
.....
public class SortFunctions{
public static void quicksort(Comparable[] a){
...
//Use the code for quicksort.
//In place of comparing a[i] and a[j]
//Use a[i].cmp(a[j])
}
}
Lets look at a Polymorphic function to copy an array.
public static void copyarray(Object[] src, Object[] tgt){
int i,limit;
limit = Math.min(src.length, tgt.length);
for(i=0;i<limit;i++){
tgt[i] = src[i];
}
}
Problem: Need to ensure that both the target array and source array are compatible with each other to copy.
src
array and storing it in an array tgt
.tgt
array we can store:
tgt
array.tgt
array.copyarray
method as Object type, then each src
and tgt
can be any type → Will cause errors during runtime.Date[] datearr = new Date[10];
Employee[] emparr = new Employee[10];
arraycopy(datearr, emparr); //Causes Runtime Error due to
//Incompatible type of objects used for copying!.
What we need: To make sure that all errors due to incompatible types are captured during compile time.
In this example → We need to make sure that source array is a subtype(also same type) of target array.
public class Ticket {...}
public class ETicket extends Ticket { ... }
Ticket[] tktarr = new Ticket[10];
ETikcet[] etktarr = new ETicket[10];
arraycopy(tktarr, etktarr) //illegal -> Because all functionalities of ETicket object is not available for Ticket object.
Object
.