Java: Get attribute of subclass without casting -
let's have superclass order , 2 subclasses vehicleorder , taskorder. both inherrit lot of methods superclass, have 1 specific field: vehicleorder has model , taskorder has task.
now, in other class, have list of order. in method, need calculations based on order's specific field.
my solution 'polluting' superclass order 2 methods getmodel() , gettask(), return null default , can overriden subclasses. other class checks null , if not null, makes calculations. doesn't feel right way though...
as don't know subclass-types of general list of orders in other class, can't cast attribute.
the other way fix using visitor pattern , feels bit of overkill.. it?
is there clean way this?
extract out common base class (or interface) both task , model can implement. let order refer type, instead of referring concrete types each order type.
this may easier said done, depending on similarities/differences of task , model. may require refactoring , abstracting more stuff work.
if proves many changes/work, fall visitor pattern.
Comments
Post a Comment