Followers

coreJava : instanceof Operator

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

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 java instanceof operator

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

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


Output:false

interface Printable {
}

class A implements Printable {
public void a() {
System.out.println("a method");
}
}

class B implements Printable {
public void b() {
System.out.println("b method");
}
}

class Call {
void invoke(Printable p) {
if (p instanceof A) {
A a = (A) p;
a.a();
}
if (p instanceof B) {
B b = (B) p;
b.b();
}

}
}// end of Call class

public class Test {
public static void main(String args[]) {
Printable p = new B();
Call c = new Call();
c.invoke(p);
}
}

No comments:

Post a Comment