It seems to work but is it concidered ‘good’ programming?
Here is an example to clarify:
public class foo{
foomethod(){do something};
}
public class foo1 extends foo{
@override foomethod(){do something};
}
public class foo2 extends foo{
@override foomethod(){do something};
}
ArrayList x /*with foo1 and foo2 objects*/
for (Object o : x){((foo)o).foomethod();}
is this concidered ‘good’ programming and if not what is a nice compact alternative?
(apart from switch(o.getClass()) if possible)
edit because I am really bad at clarifying it seems 🙂
I do mean to call the method that has been overriden and not the super method.
An alternative method for what I want to do would be:
ArrayList x /* again with foo1 and foo2 objects*/
for (Object o : x){
switch(o.getClass()){
case foo1.class:
((foo1)o).foomethod();
break;
case foo2.class:
((foo1)o).foomethod();
break;
}
}
but I want to avoid the switch statement because it makes the code much bigger and complex.
Modulo the problem with the wording of your question …
Yes, it is good programming to declare a method in a superclass, override it in a subclass, and call it polymorphicly.
It is certainly much better than using a chain of
instanceoftests or aswitchon the class name. Those approaches are considered “bad” … because they involve wiring too much knowledge of the class hierarchy into other code. For instance, if you add another subclass ofFoo, all of those switches need to be checked and potentially changed. (And the compiler won’t remind you to do it …)