0

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

Community
  • 1
  • 1
Gunjan Shah
  • 5,088
  • 16
  • 53
  • 72

1 Answers1

3

It's a feature, not a bug. Compiler prevents you from you using instanceof operator in situations where it is basically impossible that it will ever be met, e.g.:

String s = "abc";
if(s instanceof Integer) {
}

s instanceof Integer can never be true. However checking is performed at compile time, so this compiles:

Object s = "abc";
if(s instanceof Integer) {
}
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • If compiler pre check the conditions then I think there is no single case when the condition will go false. – Gunjan Shah May 17 '12 at 08:49
  • Tell me a example when the condition will become false...there will not be any case due to compile time pre checking – Gunjan Shah May 17 '12 at 08:49
  • ohk ... got the solution.. it will be false in case like ...A iface2 = new SuperClass();if(iface2 instanceof Subclass)...so it will be false when we try to refer a class that is below the atctual class in the inheritance hierarchy. – Gunjan Shah May 17 '12 at 09:32