insanceof question

Why can't I get this to compile?

public class InstanceofTest {
    public static void main(String args[]){
        Double a = new Double(0.0d);
        if(a instanceof Integer){
            System.out.println("true");
        }
        else{
            System.out.println("false");
        }
    }
 }

here's what I get:
F:\>javac InstanceofTest.java
InstanceofTest.java:4: inconvertible types
found   : java.lang.Double
required: java.lang.Integer
        if(a instanceof Integer){
           ^
1 error


this kind of error doesn't make any sense to me being I thought instanceof was precisely to compare objects and simply return true or false
day7Asked:
Who is Participating?
 
objectsCommented:
The var must be an instance of a superclass of the class being tested against.
0
 
objectsCommented:
Error is because a could not possibly be an Integer

To make it compile try changing the declaration to

  Number a = new Double(0.0d);
0
 
CEHJCommented:
Would compile with

Object a = new Double(0.0d);
0
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

 
day7Author Commented:
ok, but doesn't that defeat the purpose of instanceof?  why does it matter that a couldn't be an Integer? why doesn't it just return false?
What are the rules, then? so I know how to use it correctly...I haven't seen that explained in any of the tutorials, etc. on instanceof
0
 
CEHJCommented:
>> ok, but doesn't that defeat the purpose of instanceof?

Not really. instanceof is for runtime checking not compile time.
0
 
day7Author Commented:
ok, I think I got the idea,
thanks
0
 
aozarovCommented:
>> What are the rules, then?
The compiler tries to catch as many errors as possible during compilcation time.
As said before, Becuase Double apparent type can never hold an Integer instance (due to java single inheritence), the compiler
can tell that and will ommit an error (as this line does not make any sense, if you want it to fail all the time then do if (false) instead).
If Double was an interface or a parent of Integer then the compiler will pass it as it can't tell if its wrong during compilation time.
0
 
CEHJCommented:
:-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.