Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Determining the type of an object?

 
H Melua
Ranch Hand
Posts: 172
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello

I was wondering, if I have an interface that is implemented by several classes, (lets say Shape)
and I've created an object of this type like this

Shape s;
s = new Rectangle();
// after few method calls I change the type of s to be triangle
s = new Triangle();

then how can I determine what type of shape s in this case? in other words, how can I know if s is now a triangle or rectangle?

is there a method in Java that checks the actual type of the object?

Thanks
HannaH
 
Pawan Arora
Ranch Hand
Posts: 105
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think declaring a method in another class, which will accept the argument of superclass and it's subclass at runtime is the fine solution of it. This is also called polymorphism.
[ October 24, 2008: Message edited by: Pawan Arora ]
 
Larry Frissell
Ranch Hand
Posts: 82
2
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use:

 
Bill Shirley
Ranch Hand
Posts: 457
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
and then you can call isAssignableFrom
 
H Melua
Ranch Hand
Posts: 172
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys very much
That works
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can also use the instanceof operator.

But in general, using these techniques is a sign for a design that doesn't make full use of the advantages of OOP, especially polymorphism.

Why do you feel the need to do it?
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic