Overriding protected methods in Java

23,514

Solution 1

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.

Solution 2

This is just not how inheritance works in Java.

If a method is overridden, and the overridden method is not visible, it's a compile-time error to try and call it.

You seem to expect that Java would automatically fall back to the method in the super class, but that does not happen.

I'll try and dig out the JLS later on why this is not done...

Solution 3

The problem is that at compile time you are telling Java that you want to access a protected member of a class when you do not have such access.

If you did this instead;

  A a = new B();
  a.test();

Then it would work and the overridden method will run because at compile time Java checks that you have access to A. At run time the object provided has the appropriate method so the B test() method executes. Dynamic binding or late binding is the key.

Share:
23,514

Related videos on Youtube

CromTheDestroyer
Author by

CromTheDestroyer

Updated on July 09, 2022

Comments

  • CromTheDestroyer
    CromTheDestroyer almost 2 years

    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.

    • Jeremy
      Jeremy about 13 years
      "give an error" .. Can you be more specific?
    • corsiKa
      corsiKa about 13 years
      @Kevin he's asking why he can't call a method that he has access to the super method of.
    • CromTheDestroyer
      CromTheDestroyer about 13 years
      @Jeremy: it refuses to compile: "a/Test.java:10: test() has protected access in b.B"
    • CromTheDestroyer
      CromTheDestroyer about 13 years
      @Kevin: Read the question: "doesn't that break visibility rules?"

Related