instanceof Operator in Java

instanceof operator is used to check whether a reference variable is an instance of a givan class or interface. Syntax to use instanceof is:

  • type can be a class name or even an interface name.
  • The return type of this operation is a boolean value i.e. true or false.

1. An Example

Output :

instanceof operator can be used with both classes and interfaces.


2. instanceof operator with Classes

2.1 If the object_reference is assigned null, instanceof returns false

Output :


2.2 An object of Child class is an instance of a Parent class.

Output :

 


2.3 An object of Parent class is not an instance of the Child class.

Output :

 


2.4 An object_reference of Parent class referring a Child class object is an instance of Child class.

Output :


3. instanceof operator can be used with Interfaces

3.1 object of a class that implements an interface is an instance of that interface.

Output :


3.2 Reference of an interface type refering an object of a class that implements it, is an instance of that class.

In the example below: c is a reference of type Car. It refers to an object of a class named Audi that implements Car interface. So it is an instance of Audi class.

Output :

 


4. Miscellaneous Uses

instanceof operator can be used to ensure that certain calculations happen on some specific type of data.

4.1 Downcasting with instanceof operator

In case of member(variables and methods) overriding:

  • Data members of an object are accessed according to reference type, while methods are accessed according to the referred object.
  • You will only notice the difference when an object reference of a parent class referes to an object of the child class.

Output :

if the check m2 instanceof Alphonso  wasn’t used, the downcasting ((Alphonso)m2)  would casuse java.lang.ClassCastException.

Here m1.taste refers variable from class type of m1 i.e Mango. For methods it is just opposite. m1.method-name() would refer a method from the referred object i.e Alphonso type.

You can overcome these restrictions by casting.