I am currently pursuing game development as a hobby, and have run into what seems to be a conflict in my mind regarding how to properly (using best practices) extend the Sprite class in LibGDX (or for the sake of this question, any Sprite class).
What I Would Like To Do
I would like to to create a class, Ship.java, with the constructor as follows:
// Note the lack of a Texture object in the constructor here public Ship(float startingX, float startingY){ super(new Texture(Gdx.files.internal("data/ship_texture.png")), 0, 0); this.startingX = startingX; this.startingY = startingY; } Why I Can't Do This
First, this implementation forces me to forfeit having a reference to the Texture that I am passing into the super constructor. This means that I cannot properly dispose() it later, which would lead to memory leaks later in the code.
The Problem
Since the constructor of the Sprite class forces you to specify a Texture, and I would want a Ship to always have the same Texture (thus would not want to specify it in the constructor of a Ship), I am limited to hacking together some factory method to construct the Ship.
My Current Solution
As specified above, I currently have a factory method that creates the Ship instead of using the constructor.
The Code
Below I have detailed the code I am currently using to get the Ship class instantiated. Please feel free to critique it:
// Private constructor because I do not want this method to be called ever private Ship(Texture texture, int row, int column) { // Calls the super constructor (for the Sprite class) super(texture, row, column); } // Instead, this create method returns a new instance of Ship public static Ship create(int row, int column){ // Create the new texture Texture texture = new Texture(Gdx.files.internal("data/ship.png")); // Set the LINEAR filter (might switch to NEAREST later) texture.setFilter(TextureFilter.Linear, TextureFilter.Linear); // Return a new instance of the Ship return new Ship(texture, row, column); } Why I Don't Like This Solution
I feel as though this is a very "hacky" fix, as it defeats the purpose of a constructor, and although static factory methods are good practice, I don't think it should be necessary to implement a new factory method for each object I plan to draw on the Screen.
My Question
What is the best way to extend the Sprite class (thus keeping all the helper methods that it provides), and still define the Texture that will be displayed on the object within the constructor of the Ship?
Is the current approach I am using appropriate?
Spritein the class. Extending it would not really be necessary. The reason I chose to extend it was because I just wanted a Sprite that had maybe one more function, and didn't see the need for an entire new class. \$\endgroup\$Spriteinto my class. This consideration makes my question sound silly, but hey, I learned something nonetheless! \$\endgroup\$