• Post Reply 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Devaka Cooray
  • Ron McLeod
  • paul wheaton
Saloon Keepers:
  • Tim Moores
  • Piet Souris
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Frits Walraven
  • Scott Selikoff

instanceof

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The following is a quote from The Java Language Specification (p. 504, Third Edition)

If a cast of the RelationalExpression to the ReferenceType would be rejected as a compile-time error, then the instanceof relational expression likewise produces a compile-time error.


Although the RelationalExpression three can not be casted to the ReferenceType Moof the following code does not generate a compile-time error in line 23. Who can explain?
 
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It's because you use the instanceof operator in the equals() method, where the three object is seen as Object. As far as this method is concerned, the parameter could be ANY type of object and therefore it is possible that it gets a Moof.
 
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Howdy Matthias,

seems to be one of your first postings here, so

Welcome to the Ranch!




The instanceof operator only generates a compile time error if the variable left of the "instanceof" and the type (class) right of the "instanceof" are not in the same type hierarchy.
Since Object is the superclass of all classes, there is no error in your code.

Another example:


In the outcommented line "i" is of type Integer and you try to check if it is of type String. This can never be true, because you can never assign a String object to variable i, because i is of type Integer.
Remember that variables can never change their type.

The rest of the example I think is self explaining.


Yours,
Bu.
[ October 06, 2007: Message edited by: Burkhard Hassel ]
 
What's that smell? Hey, sniff this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic