Nested classes question

K

kelvSYC

Does a class have access to the private fields and methods of a
nonstatic member class?
 
P

Paul Lutus

kelvSYC said:
Does a class have access to the private fields and methods of a
nonstatic member class?

What did your 30-second practical experiment reveal? Do you have access to a
Java compiler?
 
R

Ryan Stewart

kelvSYC said:
Does a class have access to the private fields and methods of a
nonstatic member class?
It took me about 45 seconds to test this:

public class NestedAccess {
public static void main(String[] args) {
AccessMe am = new NestedAccess().new AccessMe();
System.out.println(am.x);
System.out.println(am.getX());
}

class AccessMe {
private int x = 5;

private int getX() {
return x;
}
}
}

The answer is yes.
 
C

Chris Smith

kelvSYC said:
Does a class have access to the private fields and methods of a
nonstatic member class?

The specific rule (from JLS 6.6.1, near the bottom of the section) is
that private members are accessible from anywhere with the body of the
top-level class that contains them. Since the entire nested class is
within the body of that top-level class, its private members are
accessible.

--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 

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

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,678
Members
48,796
Latest member
Greg L.

Latest Threads

Top