instanceOf operator

PREVIOUS

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 operatorbecause 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

Let's see the simple example of instance operator where it tests the current class.
  1. class Simple1{  
  2.  public static void main(String args[]){  
  3.  Simple1 s=new Simple1();  
  4.  System.out.println(s instanceof Simple);//true  
  5.  }  
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 java instanceof operator

  1. class Animal{}  
  2. class Dog1 extends Animal{//Dog inherits Animal  
  3.   
  4.  public static void main(String args[]){  
  5.  Dog1 d=new Dog1();  
  6.  System.out.println(d instanceof Animal);//true  
  7.  }  
  8. }  
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.
  1. class Dog2{  
  2.  public static void main(String args[]){  
  3.   Dog2 d=null;  
  4.   System.out.println(d instanceof Dog2);//false  
  5.  }  
  6. }  
Output:false

Understanding Real use of instanceof in java

Let's see the real use of instanceof keyword by the example given below.
  1. interface Printable{}  
  2. class A implements Printable{  
  3. public void a(){System.out.println("a method");}  
  4. }  
  5. class B implements Printable{  
  6. public void b(){System.out.println("b method");}  
  7. }  
  8.   
  9. class Call{  
  10. void invoke(Printable p){//upcasting  
  11. if(p instanceof A){  
  12. A a=(A)p;//Downcasting   
  13. a.a();  
  14. }  
  15. if(p instanceof B){  
  16. B b=(B)p;//Downcasting   
  17. b.b();  
  18. }  
  19.   
  20. }  
  21. }//end of Call class  
  22.   
  23. class Test4{  
  24. public static void main(String args[]){  
  25. Printable p=new B();  
  26. Call c=new Call();  
  27. c.invoke(p);  
  28. }  






No comments:

Post a Comment