Java instanceof
The java instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface).
The instanceof in java 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 has null value, it returns false.
Simple example of java instanceof
- class Simple1{
- public static void main(String args[]){
- Simple1 s=new Simple1();
- System.out.println(s instanceof Simple);//true
- }
- }
Output:true
instanceof in java with a variable that have null value
If we apply instanceof operator with a variable that have null value, it returns false. Let's see the example given below where we apply instanceof operator with the variable that have null value.
- class Dog2{
- public static void main(String args[]){
- Dog2 d=null;
- System.out.println(d instanceof Dog2);//false
- }
- }
Downcasting :
Example of downcasting with instanceof operator :
class Parent {}
public class Child extends Parent
{
public void check()
{
System.out.println("Successfully Casting");
}
public static void show(Parent p )
{
if(p instanceof Child)
{
Child b1= (Child)p;
b1.check();
}
}
public static void main(String args[])
{
Parent p=new Child();
Child.show(p);
}
}
Output : Successfully Casting
More Example of instanceof operator :
class Parent {}
class child1 extends Parent {}
class child2 extends Parent{}
class test
{
public static void main(String args[])
{
Parent p=new Parent ();
child1 c1= new child1();
child2 c2= new child2();
System.out.println(c1 instanceof Parent);
System.out.println(c2 instanceof Parent);
System.out.println(p instanceof child1);
System.out.println(p instanceof child2);
p=c1;
System.out.println(p instanceof child1);
System.out.println(p instanceof child2);
p=c2;
System.out.println(p instanceof child1);
System.out.println(p instanceof child2);
}
}
Output:
true
true
false
false
true
false
false
true

No comments:
Post a Comment