Possible Duplicate:
instanceof - incompatible conditional operand types
I am testing JAVA "instance of" operator for brush up my mind. I see that the keyword is used to check if a reference is instance of a class or not.
But we use a reference to compare with a class that is not having any IS-A relationship with the class then it gives compile time error.
See the following code :
package instanceofdemo;
public class Sample_1 {
public static void main(String a[]){
A iface = new Subclass();
///HERE INTERFACE OBJECT IS DOWNCASTED TO SUBCLASS
if(iface instanceof SuperClass){
System.out.println("iface instanceof SuperClass");
}
///HERE INTERFACE OBJECT IS DOWNCASTED TO SUBCLASS
if(iface instanceof Subclass){
System.out.println("iface instanceof Subclass");
}
if(iface instanceof A){
System.out.println("iface instanceof A");
}
Subclass sub = new Subclass();
//SO INSTANCE OF ONLY WORKS WITH IS-A RELATION SHIP IN BI-DIRECTIONAL WAY
//IT WILL GIVE COMPILE TIME ERROR, IF YOU TRY TO USE INSTANCE-OF WITH NON-RELATED CLASS
if(sub instanceof Independent){
}
}
}
interface A{
}
class SuperClass implements A {
}
class Subclass extends SuperClass{
}
class Independent{
}
In above code : when it gives compilation error at if(iface instance of Independent)
line bcoz iface is not in "IS-A" relationship with Independent.
Then what is the exact use of insatance of keyword ? If its used only with "IS-A" relationship then...where are the changes for the if condition to be false ??