程序的输出。试题类型

Output of a program. Test type of questions

有人可以向我解释为什么输出是 "DDAC" 而不是 "DAC" 吗?为什么它打印 "D" 两次?

class A {
    String text = "A";
    String getText(){
        return text;
    }
    public static void main(String[] args) {
        System.out.println((new B()).getText());
    }
}
class B extends A{
     B(){
         text = getText() + "C";
     }
     String getText(){
         return  "D" + super.getText();
     }
}

您的代码令人困惑,因为您在不同的 class 中有两个同名的方法。您在构造函数 B() 中调用了 getText(),它从 class B 获取文本。您希望它从 class A 获取文本。我所做的只是更改名称class B 中的 getText()getBText(),并正确调用了方法。代码如下:

class ScratchPaper {
    String text = "A";
    String getText(){
        return text;
    }
    public static void main(String[] args) {
        System.out.println((new B()).getBText());
    }
}
class B extends ScratchPaper {
     B(){
         text = getText() + "C";
     }
     String getBText(){
         return  "D" + super.getText();
     }
}

输出结果如您所愿:

DAC

在代码中,如果你看到

 public static void main(String[] args) {
    System.out.println((new B()).getText());
}

先调用,调用B的构造函数即

B(){
     text = getText() + "C";
 }

这里如果看到属性text是继承自超类A 所以,当构造函数被调用时

 B(){
     text = getText() + "C";
 }
 String getBText(){
     return  "D" + super.getText();
 }

作为超类属性的文本值获取值'DAC'

text = "DAC";

现在当创建 B 的实例时,然后再次调用 B 的 getText()

**(new B()).getText()**

调用下面的代码

String getBText(){
 return  "D" + super.getText(); // here super.getText() = "DAC"
}

输出 "DDAC" !!!