Saturday, December 23, 2017

JAVA - How to check if the instance is descendant of particular class

When you have more classes and its instances, you can check, if the object instance is descendant of the particular class - or if the instance directly is particular class. For this reason use java instanceof operator.

Suppose you have this classes,
public class Car {};
public class Nissan extends Car {};
and you create this two instances:
Car car = new Car();
Nissan nissan = new Nissan();
Now you can perform test, if the particular instance is descendant of the particular class:
/* check "car - Car" */

if ( car instanceof Car )
  System.out.println( "car instance of Car = true" );
else
  System.out.println( "car instance of Car  -> false" );

/* check "car - Nissan" */

if ( car instanceof Nissan )
  System.out.println( "car instance of Nissan -> true" );
else
  System.out.println( "car instance of Nissan -> false" );

/* check "nissan - Nissan" */

if ( nissan instanceof Nissan )
  System.out.println( "nissan instance of Nissan -> true" );
else
  System.out.println( "nissan instance of Nissan -> false" );
Output:
car instance of Car = true
car instance of Nissan -> false
nissan instance of Nissan -> true
-> car is not descendant of Nissan class.

No comments:

Post a Comment