I’m kind of new to visibility and want to really internilize these concepts.
I’ve learnt that “package-private”, the default visibility in Java, allows us to see fields from classes in the same package; and that protected, apart from implying package visibility,
also allows us, from class Child
in otherPackage
, get fields declared in Parent
class in thisPackage
,
as long as we are asking for them to an instance of class Child
or a descendant.
However, this case really confuses me:
package thisPackage;
public class Parent {
protected int protectedField;
int packagePrivateField;
}
package otherPackage;
import thisPackage.Parent;
public class ChildOtherPackage extends Parent {
}
Under this situation, I would guess that this code wouldn’t work (because we are asking an instance of ChildOtherPackage
for the protected
field, and ChildOtherPackage
does not inherit from GrandChild
), but it does:
package thisPackage;
import otherPackage.ChildOtherPackage;
public class GrandChild extends ChildOtherPackage {
public void test (ChildOtherPackage c) {
System.out.println(c.protectedField);
}
}
And also, this code that I would expect to work (because classes GrandChild
and Parent
are declared in the same
package), doesn’t:
package thisPackage;
import otherPackage.ChildOtherPackage;
public class GrandChild extends ChildOtherPackage {
public void test (GrandChild g) {
System.out.println(g.packagePrivateField); // Error: packagePrivateField is not public in Parent; cannot be accessed from outside package
}
}
What’s going on here? Maybe the behaviour in the second example has to do with the fact that inheritance really represent implicit composition internally and when we ask for g.packagePrivateField
, g
asks his internal ChildOtherPackage
object for the packagePrivateField
, and in this question we are soliciting a package-private field from outside the package thisPackage
; but I’m not really sure.
Any help is really appreciated.
TL;DR: I expected (under the environment of the first two code snippets) the first code not to work and the second one to work, and neither of those happened.
Daniel Hidalgo Chica is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.