Search code examples
javaoutputsuperclass

Output of a program. Test type of questions


could someone explain to me why the output is "DDAC" and not "DAC"? Why it prints "D" two times?

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();
     }
}

Solution

  • Your code is confusing because you have two methods in different classes with the same name. You called getText() in your constructor B(), which was getting the text from class B. You wanted it to get text from class A. All I did was change the name of getText() in class B to getBText(), and called the methods correctly. Code shown below:

    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();
         }
    }
    

    And the output is how you expected:

    DAC