Java ProgramsOOPinstanceof Example

instanceof Example in Java

beginner·  OOP  ·  Polymorphism

Problem

The instanceof operator tests whether an object is an instance of a given class (or one of its subclasses) at runtime, returning true or false without throwing anything.

Given an array of employees that may include managers, check each one's actual type and print different details depending on which it is.

Input
staff = [Employee("Alice"), Manager("Bob", 5)]
Output
Alice is a regular employee Bob manages a team of 5

Java Program

Java
class Employee { String name; Employee(String name) { this.name = name; } } class Manager extends Employee { int teamSize; Manager(String name, int teamSize) { super(name); this.teamSize = teamSize; } } public class InstanceofDemo { public static void main(String[] args) { Employee[] staff = { new Employee("Alice"), new Manager("Bob", 5) }; for (Employee e : staff) { if (e instanceof Manager) { // only cast once the real type is confirmed Manager m = (Manager) e; System.out.println(m.name + " manages a team of " + m.teamSize); } else { System.out.println(e.name + " is a regular employee"); } } } }

Output

Alice is a regular employee Bob manages a team of 5

Core Logic

Testing each element with instanceof before touching any subclass-specific member avoids ever casting an object to a type it doesn't actually have.

How It Works
  1. 1staff is declared as Employee[], but its second element is actually a Manager.
  2. 2e instanceof Manager checks the object's real runtime type, regardless of what the array's declared element type is.
  3. 3Only when that check succeeds is e cast to Manager, so teamSize is only ever accessed on an object that genuinely has it.
  4. 4Every other element falls through to the plain Employee branch instead.
For staff = [Alice, Bob (Manager)], Alice fails the instanceof Manager check and prints the plain employee message, while Bob passes it and prints his team size.
💡

Key Point: Checking instanceof before casting is what keeps this safe — casting an object to a type it doesn't actually belong to throws a ClassCastException at runtime, and instanceof is the guard that rules that out first.

Key Concepts

instanceof operatorruntime type checksafe casting

Related Programs