PDA

View Full Version : worker tester that uses polymorphism


mia_tech
02-23-2009, 01:38 AM
I've been asked to create a worker tester for this Classes http://www.codingforums.com/showthread.php?t=159333 that implements polymorphism, although it was discussed on that thread, the worker tester was provided for me, now I need to implement one that uses polymorphism, which I have, I'm posting it here, b/c I'm not completely sure, although I'm calling the same method computePay(double hours), but the method changes depending on the object who calls it (polymorphism)

public class WorkerTester {

public static void main(String[] args)
{
//worker tester
SalariedWorker j = new SalariedWorker("John", 30);
SalariedWorker s = new SalariedWorker("Sam", 20);
HourlyWorker e = new HourlyWorker("Emily", 30);
HourlyWorker t = new HourlyWorker("Tom", 40);
System.out.println(j.getName()+": "+j.computePay(45));
System.out.println(s.getName()+": "+j.computePay(35.50));
System.out.println(e.getName()+": "+e.computePay(55.75));
System.out.println(t.getName()+": "+t.computePay(34.25));

}
}

Old Pedant
02-23-2009, 06:09 AM
No, that does not in the least exhibit or test polymorphism.

But it would be a simple change to make it do so:


public class WorkerTester {

public static void main(String[] args)
{
// Worker tester...just what it says: test the root class Worker
Worker j = new SalariedWorker("John", 30);
Worker s = new SalariedWorker("Sam", 20);
Worker e = new HourlyWorker("Emily", 30);
Worker t = new HourlyWorker("Tom", 40);
System.out.println(j.getName()+": "+j.computePay(45));
System.out.println(s.getName()+": "+s.computePay(35.50));
System.out.println(e.getName()+": "+e.computePay(55.75));
System.out.println(t.getName()+": "+t.computePay(34.25));

}
}

*NOW* you are showing how polymorphism works!

All of those variables (j,s,e,t) are declared as Worker and yet, when it comes time to invoke computePay, the *correct* version of computePay is indeed invoked.

Even better, perhaps, would have been

public class WorkerTester
{
private static void showPay( Worker w, double hrs )
{
System.out.println(w.getName()+": "+w.computePay(hrs));
}
public static void main(String[] args)
{
// Worker tester...just what it says: test the root class Worker
showPay( new SalariedWorker("John", 30), 45 );
showPay( new SalariedWorker("Sam", 20), 35.5 );
showPay( new HourlyWorker("Emily", 30), 55.75 );
showPay( new HourlyWorker("Tom", 40), 34.25 );

}
}

Now it is truly really really clear that the showPay method doesn't care what kind of Worker it is given. It is, as required, completely polymorphic.

But the first version really adequately demonstrates the principle, I believe.