Why is it that I have access to and visibility of protective fields inside classes that share the same parent? I always figured that protected could only be accessed through the parent or the child itself not outside in any way.
class Parent {
protected int age;
}
class Sister extends Parent { }
class Brother extends Parent {
public void myMethod(Sister sister) {
//I can access the field of my sister,
// even when it is protected.
sister.age = 18;
// Every protected and public field of sister is visible
// I want to reduce visibility, since most protected fields
// also have public getters and some setters which creates
// too much visibility.
}
}
So I guess it's only protected from outside of the family. Why is this and how can I have something hidden even from family members other then the direct parent and the child? To me it seems we're lacking an access member modifier. Something like family
should actually be protected
and protected should be hidden from all but the child and parent. I'm not asking anyone to rewrite Java, just noticing.
That is because the classes Parent
, Brother
and Sister
are in the same package. Members within the same package are always visible, except with the private
modifier.
This code:
public class Sister {
void someMethod() {
Brother brother = new Brother();
brother.age = 18;
}
}
means you are working in the Sister
class, and from there, you're trying to access the age
member of the Brother
class. Brother
has nothing to do with Sister
, except the fact that they accidentally extend the same parent class.
The only reason accessing the age
member is valid, is because Brother
and Sister
are within the same package. Try to move either Brother
or Sister
to another package, and you'll see that the compiler starts complaining.