• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Method to build subclass objects

 
Alex Birmingham
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Okay.... I have a text-file that holds the information to create a series of 'rooms.' Type, X, Y, name, description, exits. Here is part of the text-file:


townRoom:0:0:Townsquare:Lots of birds and stuff!:north/south/east
wildernessRoom:-20:-10:A Ravenous Forest:Geez things are not looking good for you!:north/south


I want to create a builder that instantiates Room objects based on that information, but not just Room objects, townRoom objects, or wildernessRoom objects, or whatever subclass the specific room is. So I did this:



Which works fine, except for the fact that because the actual instantiation occurs within if(), the compiler can't actually find newRoom when I start in with my setters. In other words, it doesn't trust that newRoom actually exists. So then I thought I might create the object above my if statement, and then use the if statement to correctly cast it, except that apparently I can't cast a superclass as a subclass. I've been wracking my brain trying to come up with another angle to go about this, but I'm out of ideas =/

Furthermore I'm concerned about the fact that this seems to indicate that I have to create an 'object-builder' method for every single one of my subclasses? What about when I'm creating monster objects, and there are 200 different types of monsters?
[ June 05, 2008: Message edited by: Alex Birmingham ]
 
fred rosenberger
lowercase baba
Bartender
Posts: 12196
35
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
by the time you get to your setters, the object DOESN'T exist. The reference has gone out of scope, so the object is lost and available for garbage collection.

you need to do something like this:



you can make your reference the superclass type, and declare it before you start your if block. note that you don't NEED to cast it. This is what polymorphism is all about. you create teh wildernessRoom, which IS a room, so the reference is valid. when you then call the setters or whatever, the subclasses version will run automatically (if they have indeed been overridden).
[ June 05, 2008: Message edited by: fred rosenberger ]
 
Alex Birmingham
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks!
[ June 05, 2008: Message edited by: Alex Birmingham ]
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As an aside, the general convention is to have class names start with an uppercase letter. Not following that convention will make your code considerably harder to read for others.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic