So, this might sound a bit weird but let me explain. I have a super class that requires multiple parameters. One such parameter is a BufferedImage
object. Now obviously, to initialize this BufferedImage
in the child class to use as a parameter, I need to use try and catch blocks. The only way I can do that is in a method of the child class called in the constructor. The problem is, the super()
constructor must be the first thing in the child class constructor. So I can't call the method to initialize my BufferedImage
before calling super()
. How can I initialize my BufferedImage
object correctly before using it as a parameter when calling super()
in my child class constructor?
Example: Super/Parent Class
public class CombatEntity {
BufferedImage sprite;
public CombatEntity(String name, BufferedImage sprite) {
//do something
}
}
Example: Child Class
public class Batman {
BufferedImage sprite;
Batman() {
super("Bruce Wayne", sprite); //sprite hasn't been properly initalized
}
void getSprite() { //I need to call this method before super in order to initalize my image
try {
File f = new File("Batman.png");
sprite = ImageIO.read(f);
}
catch(Exception e) {
//whatever
}
}
}
Do something like this:
At the parent class create normal constructor, which takes name and sprite parameters. Generate getters and setters method following JavaBeans specification.
CombatEntity:
public class CombatEntity {
protected String name;
protected BufferedImage sprite;
public CombatEntity(String name, BufferedImage sprite) {
this.name = name;
this.sprite = sprite;
}
/*
* Getters and Setters
*/
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BufferedImage getSprite() {
return sprite;
}
public void setSprite(BufferedImage sprite) {
this.sprite = sprite;
}
}
In Batman (child) class create two constructors - one with no parameters, which you can use to create Batman object before you initialize sprite image, and second similiar to parent constructor. When you invoke constructor with no parameters, it invoke parent constructor and set it's parameters to default. Then you can execute generateSpriteImage(String spriteImagePath) to create sprite image from injected path.
Batman:
public class Batman extends CombatEntity{
//Default constructor with no parameters
public Batman(){
super("", null);
}
public Batman(String name, BufferedImage sprite){
super(name, sprite);
}
public void generateSpriteImage(String spriteImagePath) {
try {
File file = new File(spriteImagePath);
this.sprite = ImageIO.read(file);
}
catch(Exception e) {
//whatever
}
}
}
Hope this will help you.