【发布时间】:2015-12-22 21:10:31
【问题描述】:
所以,这听起来可能有点奇怪,但让我解释一下。我有一个需要多个参数的超类。一个这样的参数是BufferedImage 对象。现在很明显,要在子类中初始化这个 BufferedImage 以用作参数,我需要使用 try 和 catch 块。我能做到这一点的唯一方法是在构造函数中调用的子类的方法中。问题是,super() 构造函数必须是子类构造函数中的第一件事。所以我不能在调用super()之前调用方法来初始化我的BufferedImage。在子类构造函数中调用super() 时,如何在将BufferedImage 对象用作参数之前正确初始化它?
示例:超级/父类
public class CombatEntity {
BufferedImage sprite;
public CombatEntity(String name, BufferedImage sprite) {
//do something
}
}
示例:子类
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
}
}
}
【问题讨论】:
标签: java inheritance constructor superclass