kaesaecracker
kaesaecracker

Reputation: 69

Inheritance and static factory methods

I have programmed a java.util.logging.Formatter (named OneLineFormatter) for my console outputs. It has two static factory methods, both call the private constructor.

Now I wanted to program a second one for debugging purposes (named DebugFormatter), which only overrides the method formatRecord in OneLineFormatter so the traces are printed too instead of just the localized message and the class.

Eclipse warned me that the super constructor OneLineFormatter() is undefined and I have to invoke another constructor. I googled the problem and found this: Java error: Implicit super constructor is undefined for default constructor on StackOverflow. But I do not want to create a public constructor because that would be against the factory principle. The factory methods and the constructor can be the same (the DebugFormatter factory methods should create a new DebugFormatter instead of a OneLineFormatter though).

If you need some more info just ask. Thanks for your help in advance!

The code:

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>}
}

And the second class:

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>} 

}

EDIT 1: added code EDIT 2: corrected code

Upvotes: 0

Views: 1209

Answers (1)

SomeJavaGuy
SomeJavaGuy

Reputation: 7347

You could just make the constructor for OneLineFormatter package-private or protected. This way you could reduce the access to the constructor to a point that fits your needs

OneLineFormatter(String rootName) {
    this.rootName = rootName;
}
// OR 
protected OneLineFormatter(String rootName) {
    this.rootName = rootName;
}

Upvotes: 1

Related Questions