Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding protected methods in Java

Test.java

package a;
import b.B;
public class Test {
    public static void main(String[] v) {
        new A().test();
        new B().test();
    }
}

A.java:

package a;
public class A {
    protected void test() { }
}

B.java:

package b;
public class B extends a.A {
    protected void test() { }
}

Why does new B().test() give an error? Doesn't that break visibility rules?

B.test() is invisible in Test because they're in different packages, and yet it refuses to call the test() in B's superclass which is visible.

Links to the appropriate part of the JLS would be appreciated.

like image 787
CromTheDestroyer Avatar asked Apr 12 '11 15:04

CromTheDestroyer


1 Answers

Here you go JLS on protected keyword: JLS protected description and JLS protected example.

Basically a protected modifier means that you can access field / method / ... 1) in a subclass of given class and 2) from the classes in the same package.

Because of 2) new A().test() works. But new B().test() doesn't work, because class B is in different package.

like image 188
pajton Avatar answered Oct 02 '22 23:10

pajton