instanceof operator
The instanceof Operator in Java
The instanceof operator in Java is used to test whether an object is an instance of a specific class or a subclass of that class. It helps to ensure type safety and avoid ClassCastException during runtime by checking the type before performing operations that depend on the specific class.
Basic Syntax
The syntax for using the instanceof operator is:
object instanceof ClassName
objectis the reference to the object being tested.ClassNameis the class or interface name.
The instanceof operator returns true if object is an instance of ClassName or its subclass; otherwise, it returns false.
Example
Here's a simple example to illustrate the use of instanceof:
class Animal {
// Some properties and methods
}
class Dog extends Animal {
// Some properties and methods
}
public class InstanceOf {
public static void main(String[] args) {
Animal a = new Animal();
Dog d = new Dog();
Animal ad = new Dog(); // Dog object referenced by Animal type variable
System.out.println(a instanceof Animal); // true
System.out.println(d instanceof Dog); // true
System.out.println(d instanceof Animal); // true
System.out.println(a instanceof Dog); // false
System.out.println(ad instanceof Animal); // true
System.out.println(ad instanceof Dog); // true
}
}
Explanation
a instanceof Animalreturnstruebecauseais an instance ofAnimal.d instanceof Dogreturnstruebecausedis an instance ofDog.d instanceof AnimalreturnstruebecauseDogis a subclass ofAnimal.a instanceof Dogreturnsfalsebecauseais not an instance ofDog.ad instanceof Animalreturnstruebecauseadis an instance ofAnimal(it references aDogobject which is a subclass ofAnimal).ad instanceof Dogreturnstruebecauseadis actually referencing aDogobject.

Comments
Post a Comment