Win a copy of Java Database Connections & Transactions (e-book only) this week in the JDBC forum!
    Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Knute Snortum
  • Paul Clapham
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Frits Walraven
Bartenders:
  • Ganesh Patekar
  • Tim Holloway
  • salvin francis

A curious case of instanceof keyword usage in JDK 1.5  RSS feed

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Report post to moderator
Hello,

As most of us know the instanceof keyword can be used to test if an object is of a specified object type. And the syntax for its common usage is as follows -
if (objectReference instanceof type).

Recently i came across a code piece on which the instanceof keyword returns an unexpected result. My The piece of code is following.

class Cat { }
class Dog {
public static void main(String [] args) {
Dog d = new Dog();
System.out.println(d instanceof Cat);
}
}


The weird part about the code is instead of returning false, the instanceof keyword triggers a compile error with the following message -

Dog.java:5: inconvertible types
found : Dog
required: Cat
System.out.println(d instanceof Cat);
^
1 error


Does anyone know -
1) why this error comes and
2) why the instanceof keyword doesnt return a false value.


Any help is very much appreciated.
Prince P V
 
Ranch Hand
Posts: 84
Eclipse IDE Hibernate Spring
  • Mark post as helpful
  • send pies
  • Report post to moderator
It's a Compiler error because it knows that a Dog would never be a Cat, but if you change
the Type of the Reference to Object like the sample below it will compile gratefully



regards,
 
Sheriff
Posts: 21747
102
Chrome Eclipse IDE Java Spring Ubuntu VI Editor Windows
  • Mark post as helpful
  • send pies
  • Report post to moderator
Prince,

Please read your private messages regarding an important announcement.

Thank you,

Rob
 
Rob Spoor
Sheriff
Posts: 21747
102
Chrome Eclipse IDE Java Spring Ubuntu VI Editor Windows
  • Mark post as helpful
  • send pies
  • Report post to moderator
And even more, this is a duplicate thread.
Please Use One Thread Per Question.
 
He's dead Jim. Grab his tricorder. I'll get his wallet and this tiny ad:
how do I do my own kindle-like thing - without amazon
https://coderanch.com/t/711421/engineering/kindle-amazon
    Bookmark Topic Watch Topic
  • New Topic
Boost this thread!