0

I have observed some strange (to me) behaviour on protected member(s).

Namely, I certainly have an understanding of main distinction between package-private and protected, which is package-private + access from the subclass, disregarding of the latter's package.

Although, I have observed this:

  • protected member of the superclass, is accessible through inheritance, in the subclass (as if the members were defined into subclass);
  • protected member of the superclass, is accessible via subclass instance (but only within subclass scope, not on the instance of subclass created somewhere else);
  • X protected member of the superclass, is NOT accessible via superclass instance, created in the subclass; however, if the protected member is static, then it's accessible on both - superclass and subclass definitions, and it's accessible anywhere (which is not the case in accessing protected instance member on the subclass instance, outside of the subclass itself).

I know, this all might be a bit messy read, but that's what I feel, as well, in my mind now - mess. I thought I have been understanding all the deep-granularities of protected modifier, but it seems something makes me a bit confused.

package com.package1;

public class SuperClass {

    protected void protectedMethod() {
    }


    protected static void staticProtectedMethod() {
    }

}
package com.package2;

import com.package1.SuperClass;

public class SubClass extends SuperClass {
    
    public static void subClassStaticMethod() {
        staticProtectedMethod(); //OK
    }
    
    public void subClassInstanceMethod() {

        protectedMethod(); //inheritance, compiles OK
        
        new SubClass().protectedMethod(); //Compiles OK

        //but
        new SuperClass().protectedMethod(); //Does NOT compile..
        
        //although with respect to static protected members, both work fine:
        SuperClass.staticProtectedMethod(); //OK
        SubClass.staticProtectedMethod(); //OK
    }
}

Any clarification, please?

Why the language design restricts protected member access on the superclass?

Why static members exhibit different behaviour and permits protected member access on both - subclass and superclass?

Why protected member can't be accessed on the subclass, outside of the subclass?

What am I missing in my understanding of protected access modifier?

Giorgi Tsiklauri
  • 8,246
  • 8
  • 35
  • 56

0 Answers0