I'm trying to pass a class instance into a constructor of another class and vise versa. I would like to do this:
static Map map = new Map(hero);
static Hero hero = new Hero(map);
I'm running this code inside my Game class. How do I go about correctly implementing the above code? Is there a better way to go about it?
EDIT:
I think what I really want is lazy loading, like if map is null then make it; otherwise, don't make it. How do I do this in Java?
You would probably do it via two-stage initialisation.
e.g.
static Map map = new Map();
static Hero hero = new Hero();
map.setHero(hero);
hero.setMap(map);
And then add guards to the relevant functions to throw a 'not fully initialised' exception if they are called before setMap / setHero
Well, the above syntax would not compile, you'd get a illegal forward reference compile error.
What you can do is construct two objects, and then set the references e.g.
static Map map = new Map();
static Hero hero = new Hero();
// and then ...
map.hero(hero);
hero.map(map);
Of course the way you name your setters is up to you, if these would behave like true Java Bean setters, you should probably stick to that naming convention (i.e. setX() and getX()). If a Map \ Hero class in not usable before using that setter, then perhaps it's the case for the Builder Design Pattern.
Another option is to use some dependency injection library that would take care of the above things for you, behind the scenes.
The third option is to use a nested class (if it fits your design), e.g.
class Map {
class Hero { ... }
}
This way every Hero has a reference to Map available via Map.this
HTH,
elmes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With