javainheritancepolymorphismscjpocpjp

why compilation fails for that example


I was working on SCJP6 dumps when I found this confusing exercise:

Given classes defined in two different files:

package packageA;

public class Message {

String getText() { return “text”; }

}

And:

package packageB;

public class XMLMessage extends packageA.Message {

String getText() { return “<msg>text</msg>”;}

public static void main(String[] args) {

System.out.println(new XMLMessage().getText());

}

}

What is the result of executing XMLMessage.main?

A. text

B. Compilation fails.

C. <msg>text</msg>

D. An exception is thrown at runtime.

The answer was: B, but I don't understand why; I think the answer should be C.


Solution

  • If the code you posted it's the one that is in the book, the correct answer as you mentioned is C, let me explain why.

    Again, assuming you copied the code as it's shown in the book when you do, the following line:

    String getText() { return “<msg>text</msg>”;}
    

    Its not overriding the getText() method in packageA.Message class but declaring a new one, that will can be accessed for XMLMessage instances within packageB.

    This would be different if the the main method is something like:

     public static void main(String[] args) {
    
        Message message = new XmlMessage();
        System.out.println(message.getText());
    }
    

    In this case there is a compilation error since the Message.getText() methods is not exposed outside the package.