My code looks like this:
public class Hashtabledemo2 {
public static void main(String[] args) {
Hashtable myCompay = new Hashtable(10);
System.out.println("Add some employee objects to the hashtable..");
Salary e1 = new Salary("Salary1", "Palo Alto, CA",
1, 100000.00);
Hourly e2 = new Hourly("Hourly2", "Cupertino, CA", 2, 100.00);
Contractor e3 = new Contractor("Contractor3", "Milpitas, CA",3, 1000.00);
myCompay.put(new Integer(e1.hashCode()), e1);
myCompay.put(new Integer(e2.hashCode()), e2);
myCompay.put(new Integer(e3.hashCode()), e2);
System.out.println("The size of the hashtable is "+myCompay.size());
int size = myCompay.size();
for(int i=1;i<=size;i++){
/* Note that the get() method of the hashtable class returns a reference to the object
that matches the given key:
public Object get(Object key)
*/
Employee current = (Employee) myCompay.get(new Integer(i));
if(current instanceof Hourly){
((Hourly) current).setHoursWorked(40);
} else if(current instanceof Contractor){
((Contractor) current ).setDaysWorked(5);
}
current.computePay();
current.mailCheck();
}
Salary, hourly, and contractor all extend the employee class.In my understanding we cast parent references to child ones not the other way round.I don't understand how this line of code works:
Employee current = (Employee) myCompay.get(new Integer(i));
this line of code is used to get the object stored at position one of the hashtable which is a Salary object.
myCompay.get(new Integer(i));
After that it is cast to Employee:
(Employee) myCompay.get(new Integer(i));
and then assigned to an Employee reference current:
Employee current = (Employee) myCompay.get(new Integer(i));
Could someone explain to me whether we are casting the object salary stored in the hashtable to an employee object and then assigning it to a employee reference current.or are we casting the reference e1 to an employee reference. Someone explain what is going on please.