Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

instance of problem

 
in.anurag Singh
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
There is an example in the book of SCJP study guide, which is not entering into my mind..


In this example the equals() method is overridden as above, but i am not able to understand how (o instanceof Moof ) is true.
I want to know if the "o" is of Moof Type or the Object Type..?
 
Vijitha Kumara
Bartender
Posts: 3913
9
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"o" is of type Object, but the method checks in the first part of the expression in "if" whether the reference gets passed in to the method is of type "Moof".
 
in.anurag Singh
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if "o" is of type Object then,
how (o instanceOf Moof ) is true,
because
(Parent insanceOf child) is illegal.
I am just confusing, please help..and explain..
 
Vijitha Kumara
Bartender
Posts: 3913
9
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if "o" is of type Object then, how (o instanceOf Moof ) is true,

No, "o" in here is a method local variable, think of it as a place holder. At the runtime the code calling this method passes a reference which might/might not be of type "Moof". Hence it should be verified before proceed further. Read more about variables here.
 
Campbell Ritchie
Sheriff
Posts: 48404
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For the instanceof operator, try the Java™ Language specification, page 320 and page 385. Note it returns false if a null value is passed.
Note also thatis very poor programming style when you can simply writeNote also that if you find a copy of Effective Java™ by Joshua Bloch or Angelika Langer's paper you will see how the instanceof operator can potentially be unreliable in the equals() method.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic