• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Deciding according the Class type of an object

 
ali honarmand
Ranch Hand
Posts: 32
Java Netbeans IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
How can I setup my decision upon Class type of an object like:



Any object oriented related notes admired .
 
Rob Spoor
Sheriff
Pie
Posts: 20545
56
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ralph Cook
Ranch Hand
Posts: 479
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20545
56
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 32
Java Netbeans IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic