Why there is an error in the commented line, because the protesters of the protected class are available to classes in the same package and subclasses in other packages.

package one; public class One { protected int val; } 

If you create the same class in the package one , then there will be no error in the commented line. For a static variable in both cases there will be no error.

 package two; import one.One; public class Two extends One{ private One o = new One(); //private int val = o.val; } 

    2 answers 2

    In addition to this correct answer , a few words about motivation.

    If the derived class would have access to protected fields of any object of the base type, it would be very easy to bypass the encapsulation. Indeed, suppose you have an object of type A , and a protected x field. Then you could access x from any point of the code using such a simple trick:

     class FakeA extends A { public void SetXFor(A obj, int x) { obj.x = x; } } new FakeA().SetXFor(obj, 42); 

    To prevent such tricks, access to protected members is limited to the current instance of the object.

    • Doesn't the encapsulation break access to the field from the classes of the package? - jisecayeyo
    • one
      From my point of view - yes, it breaks. Java developers seem to believe that the package is a collection of closely related code, so they allowed it. - VladD

    At first glance, the error in your code is not visible, but it is.

    You are right, protected properties are available for heirs in other packages. But look at how you are calling from Two to the parent:

     private One o = new One(); 

    You do not use family ties here. You just created a new instance of the class that is not related to yours. If you want to refer to the parent class, you should use the super keyword:

     private int val = super.val;