I am currently implementing a function, using the superclass as a parameter.
For example:
private void foo(Parent parent) {
if(parent.getClass() == Child1.class) {
Child1 c1 = (Child1) parent;
System.out.println(c1.getChild1Attribute());
}
else if(parent.getClass() == Child2.class) {
Child2 c2 = (Child2) parent;
System.out.println(c1.getChild2Attribute());
}
else if(parent.getClass() == Parent.class) {
System.out.println(parent.getParentAttribute());
}
}
Is this a bad idea?
I've read some threads here saying that using getClass()
or instanceof
is bad design:
It is not necessarily a bad design, but it is an indication that something wrong may be going on.
Your specific case looks bad, because it appears that a single method is aware of multiple classes. This could be an indication that you are missing an overload possibility, or an opportunity to use one of the multiple dispatch patterns:
// Three overloads - one per target class
private void foo(Parent obj) {
}
private void foo(Child1 obj) {
}
private void foo(Child2 obj) {
}
One of the common multiple dispatch patterns is visitor pattern, see if it is applicable to the problem you're solving.
Yes, it is bad design.
Instead, you should make a single abstract method in the superclass and override it in each subclass to perform the desired action.
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