Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 323
Heat Miser Avatar asked May 29 '09 23:05

Heat Miser


People also ask

Is method a class in Java?

A Method provides information about, and access to, a single method on a class or interface. The reflected method may be a class method or an instance method (including an abstract method).

Is method and class the same in Java?

The main difference between Class and Method is that Class is a blueprint or a template to create objects while a method is a function that describes the behavior of an object.

What is class method and method in Java?

Class methods are methods that are called on the class itself, not on a specific object instance. The static modifier ensures implementation is the same across all class instances. Many standard built-in classes in Java (for example, Math) come with static methods (for example, Math.

How do you test a method in Java?

write a main method on your class, and call your test method. To check by running just write a main method and call this method with arguments. If you want to have a test case, take a look at JUnit or Mokito to write a test. There should be a way to run parts or the code without writing a main method or a test-class.


1 Answers

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.

like image 187
Dave Ray Avatar answered Oct 03 '22 20:10

Dave Ray