wood burning stoves 2.0*
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
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: 19655
    
  18

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: 19655
    
  18

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Deciding according the Class type of an object
 
Similar Threads
Can static code contain "this" keyword?
toString() method not invoked
is it possible to crete an instance without new operator? this is the smaple code i tried which dint
Widening Reference Conversation
How to typecast an object which is of unknown class type at runtime?