File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Determining the type of an object? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Make it so: Java DB Connections & Transactions this week in the JDBC forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Determining the type of an object?" Watch "Determining the type of an object?" New topic

Determining the type of an object?

H Melua
Ranch Hand

Joined: Jan 04, 2005
Posts: 172

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?

Pawan Arora
Ranch Hand

Joined: Sep 14, 2008
Posts: 105
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

Joined: May 16, 2008
Posts: 82
You can use:

Bill Shirley
Ranch Hand

Joined: Nov 08, 2007
Posts: 457
and then you can call isAssignableFrom

Bill Shirley - bshirley -
if (Posts < 30) JavaRanchFAQ);
H Melua
Ranch Hand

Joined: Jan 04, 2005
Posts: 172
Thanks guys very much
That works
Ilja Preuss

Joined: Jul 11, 2001
Posts: 14112
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?

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
subject: Determining the type of an object?
jQuery in Action, 3rd edition