I am trying to make a PrintStream that does nothing every time its methods are invoked. The code has no error apparently, but when I try to use it I get a java.lang.NullPointerException: Null output stream. What am I doing wrong?
public class DoNothingPrintStream extends PrintStream {
public static final DoNothingPrintStream doNothingPrintStream = new DoNothingPrintStream();
private static final OutputStream support = new OutputStream() {
public void write(int b) {}
};
// ======================================================
// TODO | Constructor
/** Creates a new {@link DoNothingPrintStream}.
*
*/
private DoNothingPrintStream() {
super( support );
if( support == null )
System.out.println("DoNothingStream has null support");
}
}
The problem is in the initialisation order. Static fields are initialised in the order that you have declared them ("textual order"), so
doNothingPrintStreamis initialised beforesupport.When
doNothingPrintStream = new DoNothingPrintStream();is executing,supporthas not been initialised yet, because its declaration is after the declaration ofdoNothingPrintStream. This is why in the constructor,supportis null.Your "support is null" message doesn't get printed, because the exception got thrown (at the
super()call) before it could be printed.Just switch around the orders of the declarations: