覆盖并从子类调用父方法

时间:2014-07-02 18:24:14

标签: java inheritance

我正在对PrintWriter进行子类化以添加其他功能:(每个请求添加完整的源代码)。

public class MyPrintWriter extends PrintWriter{
    public static void main(String[] args){
        MyPrintWriter mpw = new MyPrintWriter();
        mpw.print("Test...");
    }

    public MyPrintWriter(){
        super(System.out);
    }
    private void doAdditionalFunctionality(){
        super.write("**AdditionalFunctionality**");
    }

    @Override
    public void write(String s, int off, int len) {
        doAdditionalFunctionality();
        super.write(s, off, len);
    }

    @Override
    public void print(String s) {
        doAdditionalFunctionality();
        super.print(s);
    }
}

然而,当我运行它时,我得到:java.lang.StackOverflowError(双关语也意图)

在这种情况下,如何最好地应用'装饰'模式?

堆栈跟踪(根据要求)

Exception in thread "main" java.lang.StackOverflowError
at java.lang.String.length(String.java:623)
at java.io.PrintWriter.write(PrintWriter.java:473)
at util.MyPrintWriter.doAdditionalFunctionality(MyPrintWriter.java:24)
at util.MyPrintWriter.write(MyPrintWriter.java:29)
at java.io.PrintWriter.write(PrintWriter.java:473)
at util.MyPrintWriter.doAdditionalFunctionality(MyPrintWriter.java:24)
at util.MyPrintWriter.write(MyPrintWriter.java:29)
at java.io.PrintWriter.write(PrintWriter.java:473)
at util.MyPrintWriter.doAdditionalFunctionality(MyPrintWriter.java:24)
...

2 个答案:

答案 0 :(得分:2)

更改

  private void doAdditionalFunctionality(){
        super.write("**AdditionalFunctionality**");
    }

  private void doAdditionalFunctionality(){
        super.write("**AdditionalFunctionality**", 0, "**AdditionalFunctionality**".length());
    }

你的问题是super.write(String)正在调用你已经覆盖的write(String,int,int)。

答案 1 :(得分:-2)

您应该找到一种避免代码中发生递归的方法。这是我的建议:

public class MyPrintWriter extends PrintWriter{
...
    @Override
    public void write(String s){        
        super.write(doAdditionalFunctionality(s));
    }
    private String doAdditionalFunctionality(){
        String yourFormattedString = "......";
        Return yourFormattedString;
    }
}