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 the subclass of an A
object passed to a function. I can see two alternatives:
void myfunction(A myobj) {
if(myobj instanceof X)
doXStuff((X) myobj);
if(myobj instanceof Y)
doYStuff((Y) myobj);
}
or add an enum
to A
with the 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);
}
Which is better? I am leaning towards the second, because instanceof
doesn't feel right for a production application. Is there another, best way? If the second is better, is there a better place to put the enum
?
The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type. It returns either true or false.
The instanceof operator and isInstance() method both are used for checking the class of the object. But the main difference comes when we want to check the class of objects dynamically then isInstance() method will work. There is no way we can do this by instanceof operator.
It verifies whether the reference variable contains the given type of object reference or not. Java instanceof also checks whether an object reference belongs to the parent class, child class, or an interface.
Java does not have typeof operator but there's the instanceof operator to check the types. System.out.println("str" instanceof String); // true Integer a = 12 ; System.out.println(a instanceof Integer); Float f = 12.3f System.out.println(f instanceof Float); // true.
Both are bad.
Define the method in A
, override the method in X
and Y
and call that method on the object passed in. You're throwing away polymorphism, a cornerstone of object oriented programming.
abstract class A {
void doStuff();
}
class Y extends A {
@Override
void doStuff() {
// Y specific implementation
}
}
class X extends A {
@Override
void doStuff() {
// X specific implementation
}
}
Call it using
void myfunction(A myobj) {
myobj.doStuff();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With