wood burning stoves*
The moose likes Beginning Java and the fly likes A Nested Class Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "A Nested Class Question" Watch "A Nested Class Question" New topic
Author

A Nested Class Question

Gary Farms
Ranch Hand

Joined: Jun 24, 2000
Posts: 57
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

Joined: Jan 11, 2002
Posts: 203
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

Joined: May 10, 2001
Posts: 3244
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


Dave
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: A Nested Class Question
 
Similar Threads
inner class in an Interface declaration
Dan's Mock Test on Nested classes
Final method
Nested Class
Urgent!!!!!!!! private/protected interface