Java instanceof operator

In Java, instanceof operator is used to check the type of an object at runtime.

It is the means by which your program can obtain run-time type information about an object. instanceof operator is also important in case of casting object at runtime. instanceof operator return boolean value, if an object reference is of specified type then it return true otherwise false.

Example of java instanceof

class Simple {
	public static void main(String args[]) {
		Simple s = new Simple);
		System.out.println(s instanceof Simple);// true
	}
}

Downcasting with java instanceof Operator

When Subclass type refers to the object of Parent class, it is known as downcasting. If we perform it directly, compiler gives Compilation error. If you perform it by typecasting, ClassCastException is thrown at runtime. But if we use instanceof operator, downcasting is possible.

 Dog d=new Animal();//Compilation error
						

If we perform downcasting by typecasting, ClassCastException is thrown at runtime.

  Dog d=(Dog)new Animal();   //Compiles
 successfully but ClassCastException is thrown at runtime.

Possibility of downcasting with instanceof

Let's see the example, where downcasting is possible by instanceof operator.

 class Animal { }  
  
class Dog3 extends Animal {  
  static void method(Animal a) {  
    if(a instanceof Dog3){  
       Dog3 d=(Dog3)a;//downcasting  
       System.out.println("ok downcasting performed");  
    }  
  }  
   
  public static void main (String [] args) {  
    Animal a=new Dog3();  
    Dog3.method(a);  
  }  
    
 }  
	
	Output:ok downcasting performed
	

Downcasting without the use of java instanceof

Downcasting can also be performed without the use of instanceof operator as displayed in the following example:

Let's take closer look at this, actual object that is referred by a, is an object of Dog class. So if we downcast it, it is fine. But what will happen if we write:

 class Animal { }  
class Dog4 extends Animal {  
  static void method(Animal a) {  
       Dog4 d=(Dog4)a;//downcasting  
       System.out.println("ok downcasting performed");  
  }  
   public static void main (String [] args) {  
    Animal a=new Dog4();  
    Dog4.method(a);  
  }  
}  

Understanding Real use of instanceof in java

	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) {// upcasting
		if (p instanceof A) {
			A a = (A) p;// Downcasting
			a.a();
		}
		if (p instanceof B) {
			B b = (B) p;// Downcasting
			b.b();
		}

	}
}// end of Call class

class Test4 {
	public static void main(String args[]) {
		Printable p = new B();
		Call c = new Call();
		c.invoke(p);
	}
}
		
 Output: b method