instanceof
- Java course
- Intermediate
- Lesson 34/116
- 4 min
Learn type checks with instanceof.
The instanceof operator
The instanceof operator checks whether an object is an instance of a specific class. The expression object instanceof Class returns true or false. It also works in an inheritance hierarchy.
Example: Animal a = new Dog(); boolean b = a instanceof Dog;. Here a is a Dog instance, so b is true. a instanceof Cat returns false. instanceof determines an object's runtime type. In an inheritance relationship it also returns true for the superclass: a instanceof Animal is also true. This is useful for type checking before a safe cast.
Safe casting
instanceof is used to check an object's type before casting it. This prevents a ClassCastException. Check first, then cast.
Example: if (a instanceof Dog) { Dog d = (Dog) a; d.bark(); }. Here a is confirmed to be a Dog, then the cast is done. This pattern is the standard way to safely cast. Writing (Dog) a without an instanceof check throws a runtime error if a is a Cat. With the check, this risk disappears.
Practice Check types with instanceof
Define a class Animal. Define Dog extends Animal with a void bark() method whose body writes System.out.println("Woof");. Put main inside Animal; write Animal a = new Dog();, check with if (a instanceof Dog), cast with (Dog) a and call bark().
Starter code
// Define Animal and Dog classes
// Check with instanceof in main
// Cast to Dog and call barkSample solution
class Animal {
public static void main(String[] args) {
Animal a = new Dog();
if (a instanceof Dog) {
Dog d = (Dog) a;
d.bark();
}
}
}
class Dog extends Animal {
void bark() {
System.out.println("Woof");
}
}Expected output
Woof
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Animal a = new Dog(); What does a instanceof Animal return?
- null
- false
- A compile error
- true Correct answer
Explanation: Dog is a subclass of Animal; instanceof returns true.
2 Complete the instanceof check
if (a ____ Dog) {
Dog d = (Dog) a;
}
if (a instanceof Dog) {
Dog d = (Dog) a;
}
Explanation: instanceof safely checks the type.
3 Match the instanceof uses
| Term | Meaning |
|---|---|
a instanceof Dog |
Type check |
true |
Dog instance |
false |
Cat instance |
(Dog) a |
Safe cast |