• Post Reply Bookmark Topic Watch Topic
  • New Topic

Instanceof and casting objects  RSS feed

 
Steven Alvarez
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What does the keyword instanceof do? What is casting objects and what is it's purpose? Can someone please show me an easy to understand example of both? Thanks.
 
Steven Alvarez
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
anyone?
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66307
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please read this.
 
David Irwin
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Imagine a method that returns an java.lang.Object which is the super object of all Java objects. But lets say that this method sometimes returns an instance of a Foo object. If you want to check if the returned type is a Foo object and not just an object you could do something like:



Here you can see we checked if the obj object is of type Foo and if it is then we can cast the obj object from type java.lang.Object to Foo.

Note that using generics in Java 1.5 or later helps remove the need in some cases to check for types and casting (especially when using the Collections framework).

Hope this helps.
Dave
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!