有点出乎意料的是,以下代码会打印两次“Close”。通过调试器运行,似乎
MyPrintStream.close()
调用了 super.close()
,这最终导致再次调用了MyPrintStream.close()
。
import java.io.*;
public class PrintTest
{
static class MyPrintStream extends PrintStream
{
MyPrintStream(OutputStream os)
{
super(os);
}
@Override
public void close()
{
System.out.println("Close");
super.close();
}
}
public static void main(String[] args) throws IOException
{
PrintStream ps = new MyPrintStream(new FileOutputStream(File.createTempFile("temp", "file")));
ps.println("Hello");
ps.close();
}
}
为什么会发生这种情况呢?我不应该扩展PrintStream吗?