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?
Joined: Jul 01, 2004
Actually I was using 'super' as a variable name there by mistake, and changing it to 'sup' does throw a visibility error on trying to instantiate. But it does not complain about the Super.Inner reference - why?
Originally posted by Fletcher Estes: But it does not complain about the Super.Inner reference - why?
Because Sub derives form Super and thus has access to it's public AND protected members, just not the private ones. You can just as easily reference a protected static attribute e.g.
Perhaps I have misunderstood your question? [ July 07, 2004: Message edited by: Bradley Smith ]
Joined: Jul 01, 2004
I think I have a better idea now. There is a difference between static accessiblity and instance accessibility. My main problem is, if the following code is compiled (given the original source I provided):
The compiler will not allow the above - the subclass does not have direct access to to the superclass's protected methods/variables, it merely inherits them. So you can instantiate a Sub, and call the inherited methods through that Sub reference:
With static references, however, the compiler seems to allow direct rather than inherited access to the superclass's methods and variables.
Joined: Jun 21, 2004
That's kind of right. If you override method() then in your overridden "method" you can call:
But if you've got some function somewhere that just creates an instance of the base class "Super" then that function doesn't have any special rights to access protected members of that class.
It's hard to explain why things appear to be different with statics but if you take a look at this code and then build and run it then it might makes sense