Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protected member behavior once it was inherited.

I've got some doubts regarding protected identifier. In the first chapter of Sun Certified Java Programmer Study Guide by K.Sierra I found the following information:

"Once the subclass-outside-the-package inherits the protected member, that member (as inherited by the subclass) becomes private to any code outside the subclass, with the exception of subclasses of the subclass."

I provided sample code which reflects the above statement and it is absolutely clear to me.

// Parent class
package package1;

import package2.Child;
public class Parent {

    protected int i = 5;

}

// Child class
package package2;

import package1.Parent;

public class Child extends Parent {

    // variable 'i' inherited

}


package package2;

public class Neighbour {

    public void protectedTesting(){
        Child child = new Child();
        System.out.println(child.i); // no access
    }
}

I've started experimenting and made a small change - moved Neighbour to package1. And there is an access to "i" variable which is a little bit surprising for me as it is not in accordance to statement "becomes private to any code outside the subclass"

Neighbour class after change:

package package1;

import package2.Child;

public class Neighbour {

    public void protectedTesting(){
        Child child = new Child();
        System.out.println(child.i); // access!
    }
}

Please clarify it to me. Thanks.

like image 676
BartoszMiller Avatar asked Oct 12 '12 14:10

BartoszMiller


1 Answers

In short, protected is package-private as well as visible to subclasses. Even the JLS is vague on this (JLS §6.6.2):

A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.

It specifies that outside the package, only subclasses can access protected members. This implies that you can also access the variable within the package. It's poor wording, but true nonetheless that protected members have package-level visibility as well as subclass-level visibility.

See also:

  • This related question
  • The Java Trail for access control
like image 79
Brian Avatar answered Sep 26 '22 03:09

Brian