我正在尝试创建一个扩展java.io.PrintWriter的类。因为PrintWriter没有非参数构造函数,所以我创建了一个构造函数,使用super()调用以路径作为参数的父构造函数。
public class PlotWriter extends PrintWriter {
PlotWriter(String path) {
try {
super(path);
} catch (FileNotFoundException ex) {
//Exeption Handled
}
}
}编译器需要围绕super()进行异常处理。
但与此同时,它抱怨说:
Error:(14, 18) java: call to super must be first statement in constructor我怎么才能解决这个问题?
发布于 2017-05-27 22:21:45
你可以这样写:
public class PlotWriter extends PrintWriter {
PlotWriter(String path) throws FileNotFoundException {
super(path);
}
}异常应该由调用方处理,它们不打算在构造函数中处理。
public void someWhere() {
try {
PlotWriter pw = new PlotWriter(".../path/file");
} catch (FileNotFoundException ex) {
// handle exception here
}
}此外,构造函数中的第一个语句应该始终是super(...);或this(...); (如果不指定任何调用,则隐式调用super();),而且它们甚至不能同时使用。
https://stackoverflow.com/questions/44222035
复制相似问题