Java instanceof Keyword

Java Instanceof Keyword


instanceof Keyword In java
Sometimes it is useful to know the type of object during run time.
For example, you might have one thread of execution that generates various types of objects and another thread that processes these objects. In this situation, it might be useful for the processing thread to know the type of each object when it receives it. 
The instanceof keyword addresses these types of situations. The instanceof operator has this general form - 
objref instanceof type
Now we will see an Example -
Example –
// Demonstrate instanceof operator.
class A {
int i/ j ;
}
class B {
int i/ j ;
}
class C extends A
int k;
}
class D extends A
int k;
}
class InstanceOf {
public static void main(String args[]) {
A a = new A();
B b = new B();
C c = new CO ;
D d = new DO ;



if(a instanceof A)
System.out.printin("a is instance of A");

if(b instanceof B)
System.out.printin("b is instance of B");

if(c instanceof C)
System.out.printin("c is instance of C");

if(c instanceof A)
System.out.printin("c can be cast to A");

if(a instanceof C)
System.out.printIn("a can be cast to C");
System.out.printIn();
// compare types of derived types
A ๐b;
ob = d; //A reference to d

System.out.printin("ob now refers to d");

if(ob instanceof D)
System.out.printin("ob is instance of D");
System.out.printIn();
ob = c; //A reference to c
System.out.println("ob now refers to c");
if(ob instanceof D)
System.out.printin("ob can be cast to D");
else
System.out.printin("ob cannot be cast to D");
if(ob instanceof A)
System.out.printin("ob can be cast to A");
System.out.printIn();
// all objects can be cast to Object
if(a instanceof Object)
System.out.printin("a may be cast to Object");

if(b instanceof Object)
System.out.printin("b may be cast to Object");

if(c instanceof Object)
System.out.printin("c may be cast to Object");

if(d instanceof Object)
System.out.printin("d may be cast to Object");

}

}
Output -
a is instance of A
b is instance of B
c is instance of C
c can be cast to A
ob now refers to d
ob is instance of D
ob now refers to c
ob cannot be cast to D
ob can be cast to A
a may be cast to Object
b may be cast to Object
c may be cast to Object
d may be cast to Object