重写System.out.println面试题

重写System.out.println面试题

发布者:IT人在线 | 发表时间:2018/12/18 9:58:48

 根据题目中的已知条件,完成下面程序,使得输出结果为 a=10,b=10。

public class Test {

   public static void main(String[] args) {

      int a=1;

      int b=2;

      method(a,b);

        System.out.println("a="+a);

        System.out.println("b="+b);

      }

   //请在此处编写method方法

}

 

方法有两种,第一种直接写一个方法 改变a和b的值,输出就可以。如果题目要求用重写System.out.println方法完成的话这个方法就不能用了

在这里要注意的是System.exit(0);否则输出结果中会是 a=10,b=10,a=1,b=1。

public static void method(int a , int b) {

      System.out.println("a="+10);

      System.out.println("b="+10);

      System.exit(0);

   }

现在我们回到主题,用重写System.out.println方法来实现 从题目给出的内容来看 其实本题的初衷

 

public static void method(int a , int b) {

      PrintStream myStream=new PrintStream(System.out) {

        @Override

        public void println(String x) {

           if(x.startsWith("a"))

           super.println(x+"0");

           if(x.startsWith("b"))

              super.println("b="+10);

        }

      };

      System.setOut(myStream);;

   }