java - Access to protected field in field of same parent? -
why have access , visibility of protective fields inside classes share same parent? figured protected accessed through parent or child not outside in way.
class parent { protected int age; } class sister extends parent { } class brother extends parent { public void mymethod(sister sister) { //i can access field of sister, // when protected. sister.age = 18; // every protected , public field of sister visible // want reduce visibility, since protected fields // have public getters , setters creates // visibility. } } so guess it's protected outside of family. why , how can have hidden family members other direct parent , child? me seems we're lacking access member modifier. family should protected , protected should hidden child , parent. i'm not asking rewrite java, noticing.
that because classes parent, brother , sister in same package. members within same package visible, except private modifier.
this code:
public class sister { void somemethod() { brother brother = new brother(); brother.age = 18; } } means working in sister class, , there, you're trying access age member of brother class. brother has nothing sister, except fact accidentally extend same parent class.
the reason accessing age member valid, because brother , sister within same package. try move either brother or sister package, , you'll see compiler starts complaining.
Comments
Post a Comment