aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt about instanceof operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt about instanceof operator" Watch "Doubt about instanceof operator" New topic
Author

Doubt about instanceof operator

Manishk Rai
Greenhorn

Joined: Jul 06, 2007
Posts: 21
In the following piece of code .


o instanceof Moof should give result as false .Because "two" which is an objet of Moof is now assigned to Object o . So now o is the object of type Object . And Object is the parent class of all the classes so ,
Based on the above o instanceof Moof should be false ? Am i right ?
Thanks
[ December 19, 2007: Message edited by: Manishk Rai ]
Sergey Petunin
Ranch Hand

Joined: Dec 16, 2007
Posts: 44
When you assign an object of type Moof to the Object o, you don't really change the type of the actual object, you change just the type of a variable that refers to it. The real type of the object remains the same. The ability to refer to the subclass object using a superclass variable is the essense of polymorphism.

But how to define the real type of the object to which the "o" variable is referring? That's where you use the instanceof operator. During runtime, it checks that the actual type of the object is Moof, and as it is, the operator returns true.
Amit Kathpal
Greenhorn

Joined: Dec 19, 2007
Posts: 11
yes sir you are absolutly rite. as now o is an instance of Object and it is a superclass of moof so o can't be instance of moof
Serg Masow
Ranch Hand

Joined: Dec 17, 2007
Posts: 49
Hi,

unfortunately You are wrong. The reference o of the type Object can polymorphically refer to any subtype ob the class Object. And if you pass a Moof instance to the equals() method you will get a reference of type Object, which refers to the Moof instance on the heap and then o instanceOf Moof will be true.


SCJP 6.0 [95%] OCP EJBD 6.0 [93%]
Manishk Rai
Greenhorn

Joined: Jul 06, 2007
Posts: 21
Thanks serge
Amit Kathpal
Greenhorn

Joined: Dec 19, 2007
Posts: 11
thank you serg for clearing my doubt
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Doubt about instanceof operator
 
Similar Threads
instanceof
Want hepl to understand Implementin an equals()
Not able to understand the program
instance of problem
Generics and collections K&B pg 526