I have following main class and main method:
public class Main {
Peter peter = new Peter(this);
Tom tom = new Tom(this);
public static void main(String[] args) {
Main main = new Main();
System.out.println(main.peter.tom);
System.out.println(main.tom.peter);
}
}
and the following Parent class:
class Enemy {
//some variables
}
and following two child classes:
class Tom extends Enemy {
Enemy peter;
Tom(Main main) {
this.peter = main.peter;
}
}
class Peter extends Enemy {
Enemy tom;
Peter(Main main) {
this.tom = main.tom;
}
}
When the two print methods run in the main method, the first one returns a null, because the Tom wasn't created at the time it is assigned to Enemy tom
.
To solve this, I didn't assign Tom
and Peter
to Enemy
in the constructor but rather with a method after the creation of the two objects.
So more like this:
private void setEnemies(){
peter.tom = tom;
tom.peter = peter;
}
When the method is called before the println methods, it works flawlessly. My question is: Is there a way to set the enemies at object creation so I don't have to call a separate method after the objects are created?