Search code examples
javaswitch-statementinstanceof

Is it possible to use the instanceof operator in a switch statement?


I have a question of using switch case for instanceof object:

For example: my problem can be reproduced in Java:

if(this instanceof A)
    doA();
else if(this instanceof B)
    doB();
else if(this instanceof C)
    doC():

How would it be implemented using switch...case?


Solution

  • This is a typical scenario where subtype polymorphism helps. Do the following

    interface I {
      void do();
    }
    
    class A implements I { void do() { doA() } ... }
    class B implements I { void do() { doB() } ... }
    class C implements I { void do() { doC() } ... }
    

    Then you can simply call do() on this.

    If you are not free to change A, B, and C, you could apply the visitor pattern to achieve the same.