Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (4k points)
I learned that Java has the instanceof operator. Can you elaborate where it is used and what are its advantages?

1 Answer

0 votes
by (46k points)

You verify if an object is an instance of a particular class. You usually apply it, when you have a recommendation or parameter to an object that is of a superclass or interfaces standard and demands to know whether the original object has unusual another type (usually more concrete).

Example:

public void doSomething(Number param) {

  if( param instanceof Double) {

    System.out.println("param is a Double");

  }

  else if( param instanceof Integer) {

    System.out.println("param is an Integer");

  }

  if( param instanceof Comparable) {

    //subclasses of Number like Double etc. implement Comparable

    //other subclasses might not -> you could pass Number instances that don't implement that interface

    System.out.println("param is comparable"); 

  }

}

Remark that if you ought to work that operator very frequently it is usually a hint that your plan has some flaws. So in a well-designed application, you should use that operator as concise as feasible (of the way there are limitations to that common rule).

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...