aspose file tools*
The moose likes Java in General and the fly likes Deciding according the Class type of an object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Deciding according the Class type of an object" Watch "Deciding according the Class type of an object" New topic
Author

Deciding according the Class type of an object

ali honarmand
Ranch Hand

Joined: Oct 12, 2009
Posts: 32

Hi,
How can I setup my decision upon Class type of an object like:



Any object oriented related notes admired .


A. Honarmand
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19696
    
  20

1) please don't use such large fonts
2) please UseCodeTags next time

This is horrible design. A better approach would be to make the method abstract, then let each sub class implement it as they see fit. That's the polymorphic way.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Ralph Cook
Ranch Hand

Joined: May 29, 2005
Posts: 479
You may want to look at the 'instanceof' operator -- it tells you if an object is of a given class type, and handles things like inheritance and interface implementation as well.

getClass() returns a string; you can test against the string. But that won't tell you if the object's class inherits from the class you test it against, etc.

I agree with a previous poster, though not as strongly. Trying to figure out how to do this may indicate a lack of good design, and stepping back and rethinking it is probably in order. On the other hand, if you're just trying to figure out how to do this if you ever want to, I think this is your answer. And there are legitimate programming reasons for doing this, also.

rc
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19696
    
  20

Ralph Cook wrote:getClass() returns a string; you can test against the string. But that won't tell you if the object's class inherits from the class you test it against, etc.

No it doesn't. getClass() returns a Class object. The class name is retrieved through that object's getName() method. Class has a lot of other methods, including isAssignableFrom and isInstance.
ali honarmand
Ranch Hand

Joined: Oct 12, 2009
Posts: 32

ali honarmand wrote:Hi,
How can I setup my decision upon Class type of an object like:



Any object oriented related notes admired .


Thanks, I should say. I will quote the code ASAP.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Deciding according the Class type of an object