Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Java Method Overriding and Visibility [Snippet]

DZone's Guide to

Java Method Overriding and Visibility [Snippet]

While overriding methods in Java is pretty straightforward, there are a couple subtleties that do come up every now and again. We take a look at one such gotcha.

· Java Zone ·
Free Resource

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

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.

Of course, if we then overrride b() in the subclass as well, things change again. Then we will see new SubClass().a() returns “subclasssubclass” no matter whether c() is public or private.

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. Our APIs verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – to ensure accurate delivery, prevent blacklisting and identify risks in real-time.

Topics:
java ,method ,override ,visibility

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}