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
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

A curious case of instanceof keyword usage in JDK 1.5

 
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
Hibernate Eclipse IDE 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: 21972
106
Eclipse IDE Spring VI Editor Chrome Java Ubuntu 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: 21972
106
Eclipse IDE Spring VI Editor Chrome Java Ubuntu 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.
 
Politics n. Poly "many" + ticks "blood sucking insects". Tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic