Search code examples
javadefaultsemanticsprotected

Can default visibility in Java Class have a protected member?


In Java, from my point of view, it does Not make sense for a default-visible class to have a protected member. From my point to view, it does not make sense because default visibility in Java = package-level protected visibility in Java = package-level + subclass( regardless of package)

class TestClass{

 protected int addIntegers(int a, int b){

       return (a+b);
 } // end of protected addIntegers(int a, int b){

}

Am I correct to say that the above code is Nonsense?


Solution

  • You could very well have a public class Foo in the same package, extending your Base class, and another class Bar in another package, extending Foo and overriding the protected method.

    package a;
    
    class Base {
        protected void bang() {
        }
    }
    
    package a;
    
    public class Foo extends Base {
    }
    
    package b;
    
    public class Bar extends Foo {
        @Override
        protected void bang() {
        }
    }