Java instanceof operator details
This tutorial demonstrates how to use the instanceof keyword in Java to test the object type.
Tutorial info:
| Name: | Java instanceof operator details |
| Total steps: | 1 |
| Category: | Basics |
| Date: | 2011-04-09 |
| Level: | Beginner |
| Product: | See complete product |
| Viewed: | 4184 |
Bookmark Java instanceof operator details
Step 1 - Using Java instanceof operator
Java instanceof operator details
It can happen that you don’t know the exact type of the object you are working with but it would be very important to get this information. In such cases you can use the instanceof keyword. Instance of is not a function but it is an operator. Using the instanceof operator you can check if the actual object is the type you are expecting of.
Let’s see the following basic class hierarchy:
public class Animal {
public void run() {
System.out.println("Run");
}}public class Dog extends Animal {
public void bark() {
System.out.println("Bark");
}}
Now create some objects and test how the instanceof operator works. Note that how the parent-child relationship works in case of using instanceof.
public class InstanceofTest {
public static void main(String[] args) {
Animal cat = new Animal();
Animal dog = new Dog();
Dog rottweiler = new Dog();
String text = "This is a string object";
testObjectType(cat);
testObjectType(dog);
testObjectType(rottweiler);
testObjectType(text);
}public static void testObjectType(Object o){
System.out.println("--- Test object type of " + o.getClass() + " ---");
if (o instanceof Animal) {
System.out.println("The object is an Animal");
}if (o instanceof Dog) {
System.out.println("The object is a Dog");
}if (o instanceof String) {
System.out.println("The object is a String");
}}}
Tags: java instanceof operator, java instanceof, instanceof operator, java, instanceof, operator
| Java instanceof operator details - Table of contents |
|---|
| Step 1 - Using Java instanceof operator |