Search code examples
javainheritanceoverridingvisibilityprotected

Overrided method visibility in Java


Assume that we have a package "p1":

package p1;

public class A {
    protected void method() { }
}

... and we also have a package "p2":

package p2;

import p1.A;

public class B extends A { }

class Tester {
    static void run() {
        new B().method(); //compile-time error
    }
}

Now if we try to compile a whole example we'll stuck at the marked line with compile-time error: compiler just doesn't see a target method in B. Why so?


Solution

  • Since Access Modifier for A.method() is protected and B extends A, there exists protected B.method() but it is to be noted that, for protected method() in class B, method() is like an "Private Entity" for class B and only "Public Entities" can be referenced from any object and thus new B().method() gives compile time error.

    To make your code work, you can change the access modifier.

    package p2;
    
    import p1.A;
    
    public class B extends A {
    
        @Override
        public void method() {
            super.method();
        }
     }