I have two classes that are subclasses of an abstract class A:
class X extends A {}
class Y extends A {}
I would like to identify a subclass of the object Apassed to the function. I see two alternatives:
void myfunction(A myobj) {
if(myobj instanceof X)
doXStuff((X) myobj);
if(myobj instanceof Y)
doYStuff((Y) myobj);
}
or add enumin Awith different types:
abstract class A {
enum Type { X, Y };
Type type;
...
}
class X extends A {
type = Type.X;
...
}
class Y extends A {
type = Type.Y;
...
}
void myfunction(A myobj) {
if(myobj.type == Type.X)
doXStuff((X) myobj);
if(myobj.type == Type.Y)
doYStuff((Y) myobj);
}
What's better? I am inclined to the second, because it is instanceofnot suitable for a production application. Is there any other better way? If the second is better, is it better to post enum?
source
share