corbfon corbfon - 1 year ago 72
Java Question

Can a switch statement be used to determine the class of an object?

After searching SO and the web, I've yet to come up with an answer for this in Java. It's pretty simple.

I've got abstract class ParentClass. Class X and class Y both inherit from ParentClass. I've also got class

DataInputDialog extends JDialog
, which is meant to provide a user interface for entering data into class X and class Y instances. DataInputDialog class looks like below:

public class DataInputDialog extends JDialog {

public DataInputDialog(ParentClass xOrY) {
//calls super constructor, makes basic components such as
// buttons and panels that are used in either X or Y data entry


now I'd like to have a
statement that would determine what type of
was passed to
. However, I've got no clue how to accomplish that. I've tried:

switch (xOrY.getClass().getTypeName()) {
case X.class.getTypeName();

and a couple other variations, but it always comes up with an error on the case statement saying either: it has to be a constant String, or that it cannot be converted to an integer.

How do I get this switch statement to determine if
is an instance of

Answer Source

For a switch to work the value must be a primitive value, a String or an Enum value. In OO code switch statements are something of a code smell; generally indicating you have missed a chance to use polymorphism.

In functional languages you might be able to use a case statement to do what your are trying.

Java is OO so I would make use of polymorphism, you will have a cleaner design.

Polymorphism Is an OO concept that basically says that two objects/classes can be considered to "BE" the same if one is the super set of the other. That is, if the objects/classes satisfy the IS-A relationship. For example if you have a Car class, FastCar and VintageCar classes that extend Car both FastCar and VintageCar are Car classes and thus satisfy the IS-A relationship, and thus they can be used any where in code where Car can be called. The implication here is that if Car...accelerate exists then FastCar.accelerate exists and can have different characteristics from VintageCar.accelerate so when call accelerate the code doesn't need to know the subtype but will call the correct accelerate method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download