In Java, the `instanceof` operator is used to check whether an object is an instance of a particular class or implements a particular interface. It returns `true` if the object is an instance of the specified class or implements the specified interface; otherwise, it returns `false`.
Syntax:
object instanceof ClassName
or
object instanceof InterfaceName
- `object`: The object whose type is to be checked.
- `ClassName`: The name of the class.
- `InterfaceName`: The name of the interface.
Example:
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
System.out.println(a instanceof Animal); // true
System.out.println(a instanceof Dog); // true
System.out.println(a instanceof Cat); // false
}
}
In this example:
- `a instanceof Animal` returns `true` because `a` is an instance of `Animal`.
- `a instanceof Dog` returns `true` because `a` is also an instance of `Dog`.
- `a instanceof Cat` returns `false` because `a` is not an instance of `Cat`.
Usage:
- Useful for checking the type of objects before performing operations or casting.
- Helps in implementing polymorphic behavior and dynamic dispatch.
Note:
- The `instanceof` operator returns `false` if the object is `null`.
- It's often used in conjunction with conditional statements, casting, and polymorphism to write more flexible and robust code.
Comments
Post a Comment