Java - Inheritance instanceof Operator

What is instanceof Operator?

Java instanceof operator tests whether a reference variable is of type of a class or a subclass of the class at runtime.

Syntax

It takes two operands and evaluates to a boolean value true or false.


<Class Variable> instanceof <Class Name or Interface Name>

To check if a variable of Employee type refers to a Manager object at runtime, you would write

Manager mgr = new Manager();
Employee emp = mgr;
if (emp instanceof Manager) {
   // The following downcast will always succeed
   mgr = (Manager)emp;
}
else {
  // emp is not a Manager type
}

Demo

class Employee {
  private String name = "Unknown";

  public void setName(String name) {
    this.name = name;
  }//from ww  w. j  a v  a 2 s  .  c o  m

  public String getName() {
    return name;
  }
}

class Manager extends Employee {
  public void giveOrder(){
    System.out.println("order");
  }
}

public class Main {
  public static void main(String[] args) {
    Manager mgr = new Manager();
    Employee emp = mgr;
    if (emp instanceof Manager) {
       mgr = (Manager)emp;
       mgr.giveOrder();
    }
    else {
      // emp is not a Manager type
    }
  }
}

Result

Related Topics

Quiz