javacodex.com
Java Examples
Java Examples
memu home questions

Instanceof Comparison

The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

Source: (InstanceofComparison.java)

interface Car {}
class Honda implements Car {}
class Civic extends Honda {}
 
public class InstanceofComparison {
   public static void main(String[] args) {
 
      Honda honda = new Honda();
      Civic civic= new Civic();
 
      System.out.println(honda instanceof Civic);
      System.out.println(honda instanceof Car);
      System.out.println(civic instanceof Car);
   }
}
 

Output:

# java InstanceofComparison 
false
true
true

Contact: javacodex@yahoo.com