home

Use static method to initialize classes before super class constructor is called.

Java does not allow to call any method before linking super() in a constructor for good reasons. Sometime this limitation hurst. Consider to the following case: In a subclass of a hypothetical class Message you want to mangle the message before using the super constructor. The following fails:


public class BrokenSpecialMessage extends Message {
public BrokenSpecialMessage(String name) {
Calendar cal = Calendar.getInstance();
cal.roll(Calendar.DAY_OF_YEAR, -1);
String newName = MessageFormat.format(
"Yesterday at {0,date}, the message {1} was created",
new Object[]{cal, name});
super("At " + newName);
}
}


/java/BrokenSpecialMessage.java
Error: line (11) Message(java.lang.String) in Message cannot be applied to ()
Error: line (17) call to super must be first statement in constructor

This is annoying because beside this simple case the “pre”-super logic cannot be collapsed into a easy statement. The solution is to use a static class method:


class SpecialMessage extends Message {
public SpecialMessage(String message) {
super("At " + formatMessage(message));
}

private static String formatMessage(String name) {
Calendar cal = Calendar.getInstance();
cal.roll(Calendar.DAY_OF_YEAR, -1);
String newName = MessageFormat.format(
“Yesterday at {0,date}, the message {1} was created”,
new Object[]{cal, name});
return newName;
}

}

faq

{ Comments are closed! }

content
api
Bear
tools