Does Java have an "is kind of class" test method

Heat Miser picture Heat Miser · May 30, 2009 · Viewed 47k times · Source

I have a baseclass, Statement, which several other classes inherit from, named IfStatement, WhereStatement, etc... What is the best way to perform a test in an if statement to determine which sort of Statement class an instance is derived from?

Answer

Dave Ray picture Dave Ray · May 30, 2009
if(object instanceof WhereStatement) {
   WhereStatement where = (WhereStatement) object;
   doSomething(where);
}

Note that code like this usually means that your base class is missing a polymorphic method. i.e. doSomething() should be a method of Statement, possibly abstract, that is overridden by sub-classes.