You cannot override a private method. It isn’t visible if you cast A to B. You can override a protected method, but that isn’t what you’re doing here (and yes, here if you move your main to A then you would get the other method. I would recommend the @Override annotation when you intend to override,
class A extends B {
@Override
public void don() { // <-- will not compile if don is private in B.
System.out.println("hoho public");
}
}
In this case why didn’t compiler provide an error for using
t.don()which isprivate?
The Java Tutorials: Predefined Annotation Types says (in part)
While it is not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with
@Overridefails to correctly override a method in one of its superclasses, the compiler generates an error.