What is Instanceof in Java?
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.
Here Is Example
class Animal{}
class Dog1 extends Animal{//Dog inherits Animal
public static void main(String args[]){
Dog1 d=new Dog1();
System.out.println(d instanceof Animal);//true
}
}
Second Example
class Parent{ }
public class Child extends Parent
{
public void check()
{
System.out.println("Sucessfull 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);
}
}
Third Example
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); //true
System.out.println(c2 instanceof Parent); //true
System.out.println(p instanceof Child1); //false
System.out.println(p instanceof Child2); //false
p = c1;
System.out.println(p instanceof Child1); //true
System.out.println(p instanceof Child2); //false
p = c2;
System.out.println(p instanceof Child1); //false
System.out.println(p instanceof Child2); //true
}
}
Java instanceof
Reviewed by Anonymous
on
October 20, 2018
Rating:
No comments: