help with abstract class

in this code here im trying to display all the cars that need a raodworthy test. now there is an abstract class involved called HGV. within the vehicle class the testyears is different than the in the hgv class.

this takes affect in the method

vehicleNeedTest(currentYear)).

when i call this method it prints out if its a hgv twice and if the status is false. i understand that it is because there are 2 parts occuring.

yet i want it to the method without this happening please help

/**

* a method that will display all the details of the cars that need a roadworthy test

*/

publicvoid displayVehiclesThatNeedTest(int currentYear)

{

Set < String > keys = vehicles.keySet();

for ( String iD : keys)

{

Vehicle vehicle = vehicles.get(iD);

if( vehicleinstanceof HGV)

{

HGV hgv = (HGV)vehicle;

if(!hgv.vehicleNeedTest(currentYear))

{

System.out.println(hgv.toString());

}

}

if( !vehicle.vehicleNeedTest(currentYear))

{

System.out.println(vehicle.toString());

}

}

}

[1693 byte] By [mollemana] at [2007-11-27 4:26:08]
# 1

I don't know what a HGV is, but whenever you have a Collection with multiple types, there's usually some bad design nearby. It sounds to me like the HGV and Vehicle don't need to be different classes, but an attribute of the same class. (I'm assuming HGV is a type of vehicle?) The Vehicle class could have a type, and the testyears could be set dependent on that type. Then you don't need to do any type casting or checking, and can call the vehicleNeedTest method on your Vehicle list.

hunter9000a at 2007-7-12 9:34:31 > top of Java-index,Java Essentials,New To Java...
# 2

hgv's print out twice because you print them twice: first in the if-statement "if( vehicle instanceof HGV)" and then in the second if-statement directly after.

Solution: Remove the "if( vehicle instanceof HGV)" statement. You don't need to know if a vehicle is hgv or not, the second if-statement will do the right thing anyway.

jsalonena at 2007-7-12 9:34:31 > top of Java-index,Java Essentials,New To Java...
# 3
yeah i no that but in my instance variable in hgv called TESTYEARS = 4 and in vehicles its =7.so i want it to take this into account
mollemana at 2007-7-12 9:34:31 > top of Java-index,Java Essentials,New To Java...
# 4

haven't you overridden the "vehicleNeedTest" method for hgv? you don't have to do more than that

otherwise you end up with code likeif (condition)

{

do something

}

else

{

do the same exact thing

}

Message was edited by:

jsalonen

jsalonena at 2007-7-12 9:34:31 > top of Java-index,Java Essentials,New To Java...