Does an outer class have access to private elements of its innerclass?

D

Dural

My experimentation seems to say yes, but I can't seem to find it
explicitly stated so anywhere.
 
P

Patricia Shanahan

Dural said:
My experimentation seems to say yes, but I can't seem to find it
explicitly stated so anywhere.

Its stated in the JLS, 6.6.1 Determining Accessibility, "Otherwise, if
the member or constructor is declared private, then access is permitted
if and only if it occurs within the body of the top level class (§7.6)
that encloses the declaration of the member or constructor."

http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.6.1

Note that it says "body of the top level class", not the body of the
class whose member it is.

Patricia
 
D

Dural

Here's the code I wrote which seems to indicate that I can access
private fields of an inner class:

public class Ex8 {

class Ex8Inner {
private int x;
Ex8Inner(int x) {
this.x = x;
}
}
Ex8.Ex8Inner ei;
Ex8() {
ei = new Ex8Inner(10);
}
public static void main(String[] args) {
Ex8 a = new Ex8();
System.out.print(a.ei.x);
}
}
 
D

Dural

Actually this works too, and is simpler:

public class Ex8 {

public class Ex8Inner {
private int x = 5;
}
Ex8.Ex8Inner ei = new Ex8Inner();
public static void main(String[] args) {
Ex8 a = new Ex8();
a.ei.x = 8;
System.out.print(a.ei.x);
}
}
 
P

Patricia Shanahan

Dural said:
Actually this works too, and is simpler:

public class Ex8 {

public class Ex8Inner {
private int x = 5;
}
Ex8.Ex8Inner ei = new Ex8Inner();
public static void main(String[] args) {
Ex8 a = new Ex8();
a.ei.x = 8;
System.out.print(a.ei.x);
}
}

Why is this an issue? The top level class enclosing the declaration of
a.ei.x is Ex8. The accesses occur within the body of Ex8. They are
permitted according to the quote from the JLS that I posted:

"Otherwise, if the member or constructor is declared private, then
access is permitted if and only if it occurs within the body of the top
level class (§7.6) that encloses the declaration of the member or
constructor."

Patricia
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top