public class Tube { private int x; private int y; private Texture t01; private Tube[] tubes; //<---------------- private Random r; public Tube(){ r= new Random(); x = 400 ; y = 0; t01 = new Texture("tube.png"); tubes = new Tube[3]; //<------------------------------ for (int i = 0; i<tubes.length;i++){ tubes[i] = new Tube(); tubes[i].x = r.nextInt(10); tubes[i].y = r.nextInt(10); } } public void drawTube(SpriteBatch batch){ for (int i = 0; i<tubes.length;i++) { batch.draw(t01, tubes[i].x, tubes[i].y); } } 

Do I understand correctly that you cannot create an array of the Tube [] object in the same Tube class. If so, why? How else to implement it?

 Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException: java.lang.StackOverflowError at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:133) Caused by: java.lang.StackOverflowError at java.io.InputStream.<init>(InputStream.java:45) at java.io.FileInputStream.<init>(FileInputStream.java:123) at com.badlogic.gdx.files.FileHandle.read(FileHandle.java:140) at com.badlogic.gdx.files.FileHandle.readBytes(FileHandle.java:222) at com.badlogic.gdx.graphics.Pixmap.<init>(Pixmap.java:146) at com.badlogic.gdx.graphics.TextureData$Factory.loadFromFile(TextureData.java:98) at com.badlogic.gdx.graphics.Texture.<init>(Texture.java:100) at com.badlogic.gdx.graphics.Texture.<init>(Texture.java:92) at com.badlogic.gdx.graphics.Texture.<init>(Texture.java:88) 

    1 answer 1

    Generally it is possible, there is even a design pattern “Linker” which is based on this.
    You need to add elements dynamically when it is needed, and not when creating a new instance. Otherwise, when you create an instance, 3 more such ones are created, in which the same thing again three times three, 3 * 3 * 3 * 3 * 3 ... as a result, infinity. It is necessary to limit the creation of new instances, or add them outside of constructors.

    • Could you write a restriction code? - ItsGonnaBeMe
    • Well .. it completely depends on what you want to implement. At a minimum, make some sort of checkbox if an object is a child of some other, if not, create new objects, if not, create one. But these are all crutches. - BogdanBida
    • Tube [] class array - three pipes. then in the draw method draw them. - ItsGonnaBeMe
    • The fact is that each pipe ALWAYS contains 3 pipes, which in turn contain another 3 pipes, ... I hope the essence is clear? Either use another class for storing three pipes, or give one pipe 3 pipes NOT in the constructor, and for example, register a separate method for this - BogdanBida
    • I created the initTube () function and initialized an array - ItsGonnaBeMe