instanceof operator-1
The instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface).
The instanceof operator is also known as type comparison operator because it compares the instance
with type. It returns either true or false. If we apply the instanceof operator with any variable
that have null value, it returns false.
Simple example of instanceof operator
Let's see the simple example of instance operator where it tests the current class.
class Simple{
public static void main(String args[]){
Simple s=new Simple();
System.out.println(s instanceof Simple);//true
}
}
Output:true
An object of subclass type is also a type of parent class. For example, if Dog extends Animal then object of Dog can be referred by either Dog or Animal class.
Another example of instanceof operator
class Animal{}
class Dog extends Animal{//Dog inherits Animal
public static void main(String args[]){
Dog d=new Dog();
System.out.println(d instanceof Animal);//true
}
}
Output:true
No comments:
Post a Comment