While studying OCJP I came across this question of packages which surprises me. I have two simple classes classes Message and New Message each within their own packages A and B respectively as follows:
package A;
public class Message
{
String getText()
{
return "text";
}
}
And class NewMessage which is in package B and subclass of A:
package B;
public class NewMessage extends A.Message
{
String getText() {
return "New Message";
}
public static void main(String[] args)
{
System.out.println(new NewMessage().getText());
}
}
And I compile as :
javac -d . Message.java
javac -d . NewMessage.java
and run as:
java B.NewMessage
and it prints
New Message
By following this stackpost
Can a private method in super class be overriden in the sub-class?
I tried tagging the method of NewMessage with @Override
and compiling it which gave me the following error:
NewMessage.java:4: error: method does not override or implement a method from a supertype
@Override
^
which means that I am not overriding the getText()
method.
Could someone explain to me what is happening here? Is this case similar to the case of private mehthod override in the post I linked?