s sivaraman wrote:
i shouldn't get that as it's legal to access a protected member(constructor) from a subclass though it's present in different package.
Yeah, you forgot about the "responsible for implementation" requirement.
And you can easily test this by instantiating an AccessModifiers instance, and notice that the protected constructor of the superclass is called during instantiation.
Campbell Ritchie wrote:A constructor is not a member of the class, but the access regulations are the same as for members. The bit about responsible for implementation means inside a subclass object (to a first approximation), and a static method is not part of the object. Protected access does not mean access within static members of subclasses.
I don't think that I agree with this. The JLS, IMO, is referring to the executing code as the entity that is required to be "responsible for the object". This means any code; constructors, instance or static methods, instance or static initializers, or heck, even code in nested classes of the top-level class.
The concept is ... the executing/accessing code is from the AccessModifiers class, so the code must be working with some instance that IS-A AccessModifiers class (hence, it is "responsible" for it) -- and if it was, it is allowed to access protected members of that instance.
Unfortunately, in this case, it is constructor, which makes it harder to envision. If it was a protected method (or protected field) of the super class, it would have been easier to see that the static method can access it, provided it had an instance that IS-A AccessModifiers class.
Both the constructor (line 8) and the field i (line 13) are accessible in the subclass constructor and the instance method but neither appears accessible to the static main method. If I change line 19 to new SubClass&hellip, that constructor is accessible to the main method and therefore the i field is accessible to the SubClass object and it compiles nicely.
javac -d . SuperClass.java SubClass.java
SubClass.java:19: error: SuperClass(int) has protected access in SuperClass
SubClass.java:19: error: i has protected access in SuperClass
Happiness is not a goal ... it's a by-product of a life well lived - Eleanor Roosevelt. Tiny ad:
ScroogeXHTML 7.2 - RTF to HTML5 / XHTML converterhttps://coderanch.com/t/692027/ScroogeXHTML-RTF-HTML-XHTML-converter