Let’s say I have two classes, Foo
and ExtendedFoo
where ExtendedFoo
inherits from Foo
. Foo
has a method .getValue()
which returns a number, ExtendedFoo
also has .increaseValue()
which adds to the stored value (Of course, in this example, what they do is completely arbitrary). What I may want to do, is keep track of several objects from each class, and for all ExtendedFoo
Objects, run .increaseValue()
and then print out what is returned from .getValue()
from every Object.
The way I’d do it, would be something like the following:
private ArrayList<Foo> foos;
private ArrayList<ExtendedFoo> eFoos;
public static void main(String [] args) {
foos = new ArrayList<Foo>();
eFoos = new ArrayList<ExtendedFoo>();
// ...
}
public void addFoo(Foo f) {
foos.add(f);
}
public void addExtendedFoo(ExtendedFoo f) {
eFoos.add(f);
foos.add(f);
}
public void updateAndPrint() {
for(ExtendedFoo ef : eFoos) {
ef.increaseValue();
}
for(Foo f: foos) {
System.out.println(f.getValue());
}
}
Of course, the obvious problems with this are that the programmer could end up accidentally calling addFoo()
and addExtendedFoo()
without realising the real purpose. If I wasn’t to include the foos.add(f)
call to addExtendedFoo()
then it could go the other way.
What way would you go about this to be as safe as possible?
It sounds like the reason you inherit ExtendedFoo from Foo is just to reuse the method getValue(), seem like a “smell” to me. You might want to reconsider whether it’s a true inheritance relationship. Inheritance should not be abused just to reuse some methods.
In case you still want to go with this design, why don’t use instanceof, e.g.:
there’s only one list and one way to add both Foo and ExtendedFoo
private ArrayList<Foo> foos;
public static void main(String [] args) {
foos = new ArrayList<Foo>();
// ...
}
public void addFoo(Foo f) {
foos.add(f);
}
public void updateAndPrint() {
for(Foo f: foos) {
if(f instanceof ExtendedFoo) {
f.increaseValue();
}
}
for(Foo f: foos) {
System.out.println(f.getValue());
}
}