java - Visibility of protected field -
package p1; public class myclass1 { protected static string str = "ss1"; } package p2; import p1.myclass1; public class myclass2 extends myclass1 { public static void test(){ myclass1 mc1 = new myclass1(); system.out.println(mc1.str); } }
as understand it, print statement not work if string declared protected not visible different package. why work when declared static protected ?
static modifier has nothing visibility, nothing change. can't access protected member (i.e. field, method) different package, no matter if it's static or not.
but in case, myclass2 extends myclass1. can access protected members superclass. still, static has nothing this.
edit:
well, interesting case because there involved 2 separate things: 1) accessing protected members subclass in different package, 2) syntax trick allowing access static (class) members instance members.
i extend example show doing in code:
package p1; public class myclass1 { protected string protectedstring = "example"; protected static string protectedstaticstring = "example"; } package p2; import p1.myclass1; public class myclass2 extends myclass1 { public void testprotected() { myclass1 othermc1 = new myclass1(); myclass2 othermc2 = new myclass2(); string testprotected; testprotected = this.protectedstring; // ok, protectedstring inherited, it's instance member of class testprotected = super.protectedstring; // ok, it's instance member of superclass testprotected = othermc1.protectedstring; // error. can't access protected members of other instance of superclass testprotected = othermc2.protectedstring; // ok. it's inherited member of myclass2, can access if belongs other instance of class } public void testprotectedstatic() { myclass1 othermc1 = new myclass1(); myclass2 othermc2 = new myclass2(); string testprotectedstatic; testprotectedstatic = this.protectedstaticstring; // ok - syntax trick testprotectedstatic = super.protectedstaticstring; // ok - syntax trick testprotectedstatic = othermc1.protectedstaticstring; // ok - syntax trick testprotectedstatic = othermc2.protectedstaticstring; // ok - syntax trick testprotectedstatic = myclass1.protectedstaticstring; // ok - can access protected static members superclass testprotectedstatic = myclass2.protectedstaticstring; // ok - static member of class } }
now, 'syntax trick'. compiler allows accessing static members instance members:
myclass mc = new myclass(); object o = mc.static_field;
but compiled bytecode:
myclass mc = new myclass(); object o = myclass.static_field;
accessing static members in way considered bad practice because it's misleading. should access static members in static way avoid confusion while reading code.
this what's goin on in case. there static field accessed in non-static way, looked instance field. when removed static modifier, became instance member. way field accessed changed, didn't notice because of object.staticfield syntax.
Comments
Post a Comment