java - Why can't I access a protected method? -
this question has answer here:
i have question protection mechanism different packages in java. can not understand is, why method call not work!
package a; class { protected void method(){}; } package b; import a.a; class b extends { } class main extends { b b = new b(); b.method();// error: method() has protected access in package1.a } why!!
a protected member or constructor of object may accessed outside package in declared code responsible for implementation of object.
being subclass doesn't mean responsible of implementation.
here example, again jls :
package points; public class point { protected int x, y; void warp(threepoint.point3d a) { if (a.z > 0) // compile-time error: cannot access a.z a.delta(this); } }
package threepoint; import points.point; public class point3d extends point { protected int z; public void delta(point p) { p.x += this.x; // compile-time error: cannot access p.x p.y += this.y; // compile-time error: cannot access p.y } public void delta3d(point3d q) { q.x += this.x; q.y += this.y; q.z += this.z; } }
a compile-time error occurs in method delta here: cannot access protected members x , y of parameter p, because while point3d (the class in references fields x , y occur) subclass of point (the class in x , y declared), not involved in implementation of point (the type of parameter p). method delta3d can access protected members of parameter q, because class point3d subclass of point , involved in implementation of point3d.
Comments
Post a Comment