我正在尝试创建一个扩展 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
我该如何解决这个问题?
最佳答案
你可以这样写:
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();
如果您未指定任何此调用,则将被隐式调用)并且它们甚至不能同时存在。
关于java - 如何扩展 PrintWriter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44222035/