So I have a more design question and want your opinions on what is best to be done here.
Say I have three classes with simple inheritance. So in simple form -
public abstract class Base {}
public class DerivedOne extends Base {}
public class DerivedTwo extends Base {}
Now in another class I have an List<Base> objects which holds a load of random DerivedOne and DerivedTwo classes.
public class Client {
List<Base> listBase = new ArrayList<Base>();
// filled with lots of Base subclasses
}
For pretty much all operations this works fine as I override methods in DerivedOne and DerivedTwo.
However the problem comes when I add in method to DerivedTwo that is unique to just that one class like -
public class DerivedTwo extends Base {
public void uniqueMethod() {}
}
Now in my Client class I need to provide a method to call this uniqueMethod on all DerivedTwo objects in the list.
I could
public void callAllUniqueMethods() {
for(Base b : listBase) {
if(b instanceof DerivedTwo)
((DerivedTwo) B)/>.uniqueMethod();
}
}
But I consider this pattern as I mess bade code design.
I could of course also have an abstract method in the Base class and override in each subclass. However that would
mean I would be leaving the method body empty in other implementations. It also messy to me.
I also thought have interface contining unique method and only implement interface on DeriveddTwo (there could be
more classes that have unique method) but not all. However again this approach have to have an instanceof and cast
to call the method.
So really what would you suggest in this situation?
Thanks again!

New Topic/Question
Reply



MultiQuote







|