Cra*_*uin 8 java encapsulation
我在如何设置封装时无所事事.
但我的程序正在以意想不到的顺序执行.这是我相当简单的代码:
主要的":
package research.debug;
public class Main {
public static void main(String[] args) {
Boolean b = Boolean.TRUE ;
Debug.black.printVariable( b, "b" ) ;
Debug.red.printVariable( b, "b" ) ;
System.out.println( "SUPPOSED to be inbetween..." ) ;
Debug.black.println( "Hello" ) ;
Debug.red.println( "Howdie" ) ;
}
}
Run Code Online (Sandbox Code Playgroud)
"调试":
package research.debug;
public class Debug {
public static final Output black = new Output( Output.BLACK ) ;
public static final Output red = new Output( Output.RED ) ;
}
Run Code Online (Sandbox Code Playgroud)
最后,"输出":
package research.debug;
public class Output {
public static final int BLACK = 0 ;
public static final int RED = 1 ;
private int outputMode = 0 ;
public Output( int outputMode ) {
this.outputMode = outputMode ;
}
public void println( String msg ) {
if( outputMode == Output.BLACK ) {
System.out.println( "Printed with black font: " + msg ) ;
} else {
System.err.println( "Printed with red font: " + msg ) ;
}
}
public void printVariable( Object variable, String variableName ) {
println( variableName + " = \"" + variable + "\"" ) ;
}
}
Run Code Online (Sandbox Code Playgroud)
预期的产出将是:
印有黑色字体:b ="true"
印有红色字体:b ="true"
支持在...之间
印有黑色字体:你好
印有红色字体:Howdie
但相反,它超出了预期的顺序,如下所示:
印有黑色字体:b ="true"
支持在...之间
印有黑色字体:你好
印有红色字体:b ="true"
印有红色字体:Howdie
发生了什么?
编辑:有时候"假定介于两者之间"的消息会四处移动.没有我改变代码.
Mik*_*ffe 18
System.out是缓冲的,System.err不是,它们是两个不同的流,你的一些消息转到一个,一些到另一个.
因此,这些混合消息可能不会以预期的顺序出现,因为打印件System.out被延迟直到刷新缓冲区(手动或自动),而那些System.err应立即写入.
您可以通过调用flush()方法手动刷新流.