我为控制台输出编写了一个 java.util.logging.Formatter(名为 OneLineFormatter)。它有两个静态工厂方法,都调用私有(private)构造函数。
现在我想编写第二个用于调试目的的程序(名为 DebugFormatter),它仅重写 OneLineFormatter 中的 formatRecord 方法,以便打印跟踪,而不仅仅是本地化消息和类。
Eclipse 警告我 super 构造函数 OneLineFormatter() 未定义,我必须调用另一个构造函数。我用谷歌搜索了这个问题,发现了这个:Java error: Implicit super constructor is undefined for default constructor在 StackOverflow 上。 但我不想创建一个公共(public)构造函数,因为这违反了工厂原则。工厂方法和构造函数可以相同(尽管 DebugFormatter 工厂方法应该创建一个新的 DebugFormatter 而不是 OneLineFormatter)。
如果您需要更多信息,请询问。提前感谢您的帮助!
代码:
public class OneLineFormatter extends Formatter {
public static Formatter withPackageFromRoot(String rootName) {
return new OneLineFormatter(rootName);
}
public static Formatter withClassOutputOnly() {
return new OneLineFormatter("");
}
private String rootName;
private OneLineFormatter(String rootName) {
this.rootName = rootName;
}
@Override
public String format(LogRecord record){<code>}
private String formatRecord(LogRecord record{<code that I want to override>}
}
第二类:
public class DebugFormatter extends OneLineFormatter {
public static Formatter withClassOutputOnly() {
return new DebugFormatter("");
}
public static Formatter withPackageFromRoot(String rootName) {
return new DebugFormatter(rootName);
}
private DebugFormatter(String rootName) {<same as OneLineFormatter(String)>}
@Override
private String formatRecord(LogRecord record) {<code>}
}
编辑1:添加代码 编辑2:更正代码
最佳答案
您可以将构造函数设为 OneLineFormatter
package-private
或 protected
。这样您就可以减少对构造函数的访问,以满足您的需求
OneLineFormatter(String rootName) {
this.rootName = rootName;
}
// OR
protected OneLineFormatter(String rootName) {
this.rootName = rootName;
}
关于java - 继承和静态工厂方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36285031/