This post is about a little test I set up to get my head around one aspect of method overriding in Java. A method in a superclass can call either another superclass method or a subclass method, depending on the visibility of the methods involved.

These are the demo classes:

public class SuperClass { public String a() { return b(); } public String b() { return c(); } public String c() { return "superclass"; } } public class Subclass extends SuperClass { public String a() { return b() + b(); } public String c() { return "subclass"; } }





new SuperClass().a() returns “superclass”. new SubClass().a() returns “subclasssubclass”.

If we change the visibility of method c() to private, however:

new SuperClass().a() returns “superclass”. new SubClass().a() returns “superclasssuperclass”.

In other words, superclass method b() will call the subclass implementation of c() if it is visible, or the superclass implementation if it is not.