Win a copy of Java by Comparison (eBook) this week in the Java in General forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

instance of problem  RSS feed

 
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..?
 
Saloon Keeper
Posts: 4041
47
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
Saloon Keeper
Posts: 4041
47
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.
 
Sheriff
Posts: 57782
178
  • 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.
 
I've got no option but to sell you all for scientific experiments. Or a tiny ad:
Thread Boost - a very different sort of advertising
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!