There are some multiple System.out.println() in the constructor of the superclass, and I have to redirect them to PrintStream object ps using System.setOut(ps).
for example, if I have a superclass like this:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
public class SuperClass implements ActionListener{
public SuperClass(){
System.out.println("Some message");
}
public String toString(){
return "Some other message";
}
@Override
public void actionPerformed(ActionEvent event)
{
System.out.println(toString());
}
}
and a subclass like this:
import java.io.IOException;
import java.io.PrintStream;
public class SubClass extends SuperClass{
private PrintStream ps;
public SubClass(){
super();
try {
ps = new PrintStream("file.txt");
} catch (IOException e){
e.getStackTrace();
}
System.setOut(ps);
}
}
whenever the action is performed (ex. pressing a JFrame Button from superclass), the System.out.println() from actionPerformed() is redirected to PrintStream object, but the System.out.println() from the constructor is not.
Also, how can I redirect the System.out to PrintStream object AND keep the System.out? (ie printing both System.out and PrintStream)
SubClass
constructor it calls SuperClass
first, because you have to init parent first.( When you call subclass constructor, it always call parent constructor first). This question have answer about init order.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.