I have a question about the apparently inconsistent behavior of inner classes when in comes to inheritance and access control. According to Sierra and Bates,p464:
A regular inner class is a member of the outer class just as instance variables and methods are
With that in mind, could someone explain the following?:
If inner classes are supposed to behave like member variables and methods (at least in terms of access modifiers and inheritance), why can I directly refer to the inner class (above) from another class not in the same package? Should I not inherit the inner class definition, and then instantiate it through the sub class?
Originally posted by Anthony Watson: The 'protected' access modifier allows access to other classes in the same package or to inheriting classes. Since class Sub extends Super, it thus has direct access to Super's inner class.
If that's the case, then why can't I call (as is commented out in the code I listed):
Protected access means you inherit members and methods from the super class, not that you can access them directly.
I was trying to figure out your problem, based upon the code you posted. This posted code must not be the code you are really running because the posted code has a variable called 'super' that is a Java keyword and so this code would not compile. Maybe if you posted the actual code you were running, it would be more helpful.
Admittedly, I spent waaaay too much time thinking about this, but I did prove my previous statement to be correct that the subclass
has direct access to Super's inner class
and also that the subclass has direct access to protected attributes and methods of the superclass.
Here's the code (which compiles and was taken straight from my editor):
One thing to note was that I had to manually create the protectedInner class's public no argument constructor. The compiler would have created one that was protected. If the constructor was protected, then it would not be able to be called by class Sub since Sub does not inherit from protectedInner, nor is it in the same package.
I hope this answers your questions because I'm done thinking about this
Thanks for your help. I'm still not sure about the issue though. And I'm aware, as you demonstrated above, that you can call a super class's method from a subclass - but only the method that is inherited by the subclass. You cannot, for instance, in your subclass, create an instance of the super, and then try to call the protected method. That's what I mean by the subclass not having direct access.
A day job? In an office? My worst nightmare! Comfort me tiny ad!
a bit of art, as a gift, the permaculture playing cards