Link to home
Start Free TrialLog in
Avatar of day7
day7

asked on

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
Avatar of Mick Barry
Mick Barry
Flag of Australia image

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);
Would compile with

Object a = new Double(0.0d);
Avatar of day7
day7

ASKER

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
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of day7

ASKER

ok, I think I got the idea,
thanks
>> 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.
:-)