• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A Nested Class Question

 
Gary Farms
Ranch Hand
Posts: 57
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If Class A extends class B, and class A contains a nested class C, does nested class C have access to superclass B?
 
Shivaji Marathe
Ranch Hand
Posts: 203
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Best way to find out is to write some code for yourself. Declare static and instance variables in the ancestor class. Make sure you have some private, some protected, some with default access and some with public access.
Then try to access these variables from the inner class in the descendant?
You can try the same thing with methods in the ancestor .
 
Dave Vick
Ranch Hand
Posts: 3244
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Gary
From the JLS 8.1.2

Inner classes whose declarations do not occur in a static context may freely refer to the instance variables of their enclosing class.

So, in your example, since B does not enclose C, C can't access the variables of B except in that they are inherited into A.
Here is an example:

the output is:
x in B: 3
x in Test: 4
x in A: 4
y in A: 6
you can see that the inner class can access the variables but it can only get the variables that are inherited into its enclosing class. The part that did puzzle me (and the JLS didn't mention it) is that the lines A.this.y and A.this.x compiled - I half expected them not to because of the A reference in them. However, the result was what I expected in that because it doesn't enclose it you can't access it.
hope that helps
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic