Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using .getClass() regarded as a bad design?

Tags:

java

oop

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:

  • why super.getClass() in a subclass returns subclass name
  • How to determine an object's class (in Java)?
like image 700
am5a03 Avatar asked Dec 04 '22 11:12

am5a03


2 Answers

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.

like image 187
Sergey Kalinichenko Avatar answered Jan 07 '23 01:01

Sergey Kalinichenko


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.

like image 31
SLaks Avatar answered Jan 07 '23 01:01

SLaks