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
object
is the reference to the object being tested.ClassName
is 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 Animal
returnstrue
becausea
is an instance ofAnimal
.d instanceof Dog
returnstrue
becaused
is an instance ofDog
.d instanceof Animal
returnstrue
becauseDog
is a subclass ofAnimal
.a instanceof Dog
returnsfalse
becausea
is not an instance ofDog
.ad instanceof Animal
returnstrue
becausead
is an instance ofAnimal
(it references aDog
object which is a subclass ofAnimal
).ad instanceof Dog
returnstrue
becausead
is actually referencing aDog
object.
Comments
Post a Comment