Check Object Is Instance Of Class
Check Object Is Instance Of Class
When working with object-oriented programming, one of the basic tasks is checking whether an object belongs to a certain class or not. This is commonly used for determining the type of an object before performing any operations on it. In Java, there are several ways to check if an object is an instance of a class.
Using instanceof Operator
The simplest way to check if an object is an instance of a class is by using the instanceof
operator. This operator returns true
if the object is an instance of the specified class or its subclass, and false
otherwise.
class Animal {
// ...
}
class Dog extends Animal {
// ...
}
Animal animal = new Animal();
Dog dog = new Dog();
boolean isAnimal = animal instanceof Animal; // true
boolean isDog = dog instanceof Animal; // true
boolean isAnimal2 = animal instanceof Dog; // false
boolean isDog2 = dog instanceof Dog; // true
Using Class.isInstance() Method
An alternative way to check if an object is an instance of a class is by using the Class.isInstance()
method. This method takes an object as a parameter and returns true
if the object is an instance of the specified class or its subclass, and false
otherwise.
class Animal {
// ...
}
class Dog extends Animal {
// ...
}
Animal animal = new Animal();
Dog dog = new Dog();
boolean isAnimal = Animal.class.isInstance(animal); // true
boolean isDog = Animal.class.isInstance(dog); // true
boolean isAnimal2 = Dog.class.isInstance(animal); // false
boolean isDog2 = Dog.class.isInstance(dog); // true
Using Class.cast() Method
The Class.cast()
method can also be used to check if an object is an instance of a class. This method takes an object as a parameter and returns the object casted to the specified class if the object is an instance of that class, and throws a ClassCastException
otherwise.
class Animal {
// ...
}
class Dog extends Animal {
// ...
}
Animal animal = new Animal();
Dog dog = new Dog();
Animal castedAnimal = Animal.class.cast(animal); // works fine
Dog castedDog = Animal.class.cast(dog); // works fine
Animal castedAnimal2 = Dog.class.cast(animal); // throws ClassCastException
Dog castedDog2 = Dog.class.cast(dog); // works fine
These are the basic ways to check if an object is an instance of a class in Java. Choose the one that suits your needs and coding style.