Reputation: 45
I have no idea why is this happenning, it seems to be in a constant loop between creating new object and initializing it
public class App {
Character hero = new Character();
charCreation charCreation = new charCreation();
public static void main(String [] args){
App app = new App();
app.run();
}
void run(){
charCreation.charCreate();
}
}
So here App creates a new charCreation object which is this
import java.util.Scanner;
class charCreation extends App {
Scanner skan = new Scanner(System.in);
protected void charCreate(){
......
And here's the error
Exception in thread "main" java.lang.StackOverflowError
at charCreation.(charCreation.java:3)
at App.(App.java:5)
at charCreation.(charCreation.java:3)
at App.(App.java:5)
......
it goes on and on
Upvotes: 0
Views: 129
Reputation: 5140
You have an App
class with a field of type CharCreation
.
CharCreation
extends App
, so when you initialize a CharCreation
object, it will initialize the field charCreation
. And so, when the charCreation
field is initialized, it will initialize a new CharCreation
object, and so on.
It's basically a design issue you have to solve, and I think you CharCreation
class shouldn't extends the App
class, and charCreate
should return a Character
.
public class App {
Character hero = new Character();
CharCreation charCreation = new charCreation();
void run(){
hero = charCreation.charCreate();
}
}
public class CharCreation {
public Character charCreate() {
/* creates and returns the hero */
}
}
Side note:
CharCreation
and not charCreation
.Character
to name a class, it's a class which already exist in the JDK (the object counterpart of char
).Upvotes: 1
Reputation: 41200
Cyclic object creation which caused stackoverflow.
App object create charCreation instance object
charCreation object will also create App Object as it is super class.[super class object instantiate before child]
Cycle found, go on... till the stackoverflow.
Upvotes: 0
Reputation: 9945
The charCreation
class extends App
so to create it it needs to call the constructor of the superclass (App
). To construct the App
superclass, the fields of App
need to be costructed, including a new charCreation()
- and so it loops.
You need to decouple creation of a new charCreation
object from the creation of the App
instance.
Upvotes: 2
Reputation: 262494
When you create an instance of CharCreation
(fixed CamelCase for you), it will also initialize everything inherited from its superclass App
(calling the superclass constructor, initializing all the instance fields, etc). Part of that is creating another instance of CharCreation
(as well as an instance of Character
).
Infinite loop.
Maybe you want to remove that instance field from App
and make it a local variable in run
instead.
Upvotes: 4