Back to Intellij Community

InstanceofThis

java/java-impl/resources/inspectionDescriptions/InstanceofThis.html

2025.3-rc-2621 B
Original Source

Reports usages of instanceof or getClass() == SomeClass.class in which a this expression is checked.

Such expressions indicate a failure of the object-oriented design, and should be replaced by polymorphic constructions.

Example:

class Super {
  void process() {
    if (this instanceof Sub) { // warning
      doSomething();
    } else {
      doSomethingElse();
    }
  }
}

class Sub extends Super {}

To fix the problem, use an overriding method:

class Super {
  void process() {
    doSomethingElse();
  }
}

class Sub extends Super {
  @Override
  void process() {
    doSomething();
  }
}