Results 1 to 4 of 4
Thread: Object is a Subclass of
- 02-09-2010, 06:27 PM #1
Senior Member
- Join Date
- Jan 2009
- Location
- NJ, USA
- Posts
- 183
- Rep Power
- 5
Object is a Subclass of
Say I have a class Entity
Entity
I have some subclasses of that, such as
Tower
Ship
Projectile
And, Tower for example, I have a number of subclasses. I'll just say A, B, C, etc.
So, if I pass an Entity to a function, I can tell if it's a tower by using "e instanceof Tower" ... but once I know it's a Tower, how can I tell if it was made as just Tower or if it's a subclass of Tower, like A B or C, without writing out "(!(e instanceof A) && !(e instanceof B) && !(e instanceof C)))" ?
-
you can call getClass() and then compare via the equals( ... ) method as this will only be true if once class is precisely the other class.
- 02-09-2010, 07:03 PM #3
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,380
- Blog Entries
- 7
- Rep Power
- 17
- 02-10-2010, 09:42 AM #4
Moderator
- Join Date
- Apr 2009
- Posts
- 10,438
- Rep Power
- 16
Indeed, if you find yourself having to figure out what class an object you're working with is, then you probably (though not always) have a problem in your code.
Would it, for example, be more sensible to have an enumeration of TowerTypes? Each of which has certain methods implemented to handle the different rules each has?
Or have an abstract method for firing (or whatever it is you need to do), and each tower subclass has its own one?
Not knowing your requirements I'm throwing stuff out there...:)
Similar Threads
-
Subclass name to be a parameter?
By Peetahzee in forum New To JavaReplies: 6Last Post: 12-12-2009, 03:51 PM -
subclass troubles
By xf021209 in forum New To JavaReplies: 12Last Post: 04-20-2009, 11:46 PM -
superclass and subclass
By mr idiot in forum New To JavaReplies: 19Last Post: 01-03-2009, 07:29 AM -
Parsing a superclass object to subclass object dynamicly
By Andrefs in forum Advanced JavaReplies: 1Last Post: 07-22-2008, 04:27 PM -
Subclass definition
By Java Tip in forum java.langReplies: 0Last Post: 04-23-2008, 08:03 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks