1

If a method foo() exists in a base class as protected, what happens if in the subclass we define the method with the public descriptor?

Leigh
  • 28,765
  • 10
  • 55
  • 103
MedicineMan
  • 15,008
  • 32
  • 101
  • 146

3 Answers3

1

It's fine to make it more accessible. From the Java Language Specification section 8.4.8.3:

The access modifier (§6.6) of an overriding or hiding method must provide at least as much access as the overridden or hidden method, or a compile-time error occurs. In more detail:

  • If the overridden or hidden method is public, then the overriding or hiding method must be public; otherwise, a compile-time error occurs.
  • If the overridden or hidden method is protected, then the overriding or hiding method must be protected or public; otherwise, a compile-time error occurs.
  • If the overridden or hidden method has default (package) access, then the overriding or hiding method must not be private; otherwise, a compile-time error occurs.
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

If the overridden method has looser permissions (e.g. public instead of protected), any reference of that subclass will have the method as that overriden permission. If the overriden method has tighter permissions, it's a compile error.

See JLS 8.4.8.3, near the bottom ("The access modifier (§6.6) of an overriding or hiding method must provide at least as much access as the overridden or hidden method, or a compile-time error occurs").

yshavit
  • 42,327
  • 7
  • 87
  • 124
0

If you increase the access of method by changing access descriptors then there will be no problem but you can not decrease access of any method in subclass.

class A{
    protected void foo(){
    }
}

class B1 extends A{
    public void foo(){
    }
}

class B2 extends A{
    private void foo(){
    }
}

class Example{
    public void ex(){
        A b1 = new B1();
        A b2 = new B2();

        b1.foo();
        b2.foo();
    }
}

b1.foo() will not create any problem, but if we allow b2.foo() at compilation time it will fail at runtime. Because of that java never allow user to decrease access of any method while overriding of method

Lokesh Gupta
  • 304
  • 2
  • 8