0

I don't get why I cannot access parent class protected member but I can access child class protected member.

As you can see I can access subchild.x from Child class but I cannot access child.x from Subchield class.

Isn't subchild.x field also must be inaccessable?

package com.company.parentPack;
public class Parent {

    protected int x = 3;

}

package com.company.childPack;
public class Child  extends Parent {    

    public int getValueChild(Subchild subchild){
        return subchild.x;  //works without any problem.
    }

    public int getValue(Child child){
        return child.x;
    }

}

package com.company.subchildPack;
public class Subchield extends Child {

    public int getValue2(Child child){
        return child.x;  //Error: java: x has protected access in com.company.parentPack.Parent
    }
}
yanefedor
  • 2,132
  • 1
  • 21
  • 37
hellzone
  • 5,393
  • 25
  • 82
  • 148
  • this is the main Idea of `protected`. – alex Mar 21 '18 at 11:09
  • 1
    As you can see in the [documentation](https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html), `protected` makes fields and methods visible to the class and its subclasses. Its sub-subclasses aren't included. `Child` is a direct subclass of `Parent`, hence it sees `x`. `Subchild` isn't, so it cannot access `x`. – BackSlash Mar 21 '18 at 11:10

0 Answers0