I have a small query regarding inner classes and access to private fields.
Eg:
class C { private int varC; }
public class A { private int varA;
private class B { private int varB;
public void accessA { // Access private variable of A Sysout(varA); }
}
public void accessB { // Access private variable of B - why is this possible? Sysout(new B().varB);
// As expected, the below doesn't work Sysout(new C().varC); } }
I would like to know why/how class A is able to access the private field 'varB' of its inner class B. I assume that the field 'varB's scope would be confined to that of class B. Shouldn't the behaviour have been consistent with trying to access the private field 'varC' of class C from within a member function of class A?
> Hi, > > I have a small query regarding inner classes and access to > private fields. > > Eg: > > class C { > private int varC; > } > > public class A { > private int varA; > > private class B { > private int varB; > > public void accessA { > // Access private variable of A > Sysout(varA); > } > > } > > public void accessB { > // Access private variable of B - why is this > this possible? > Sysout(new B().varB); > > // As expected, the below doesn't work > Sysout(new C().varC); > } > } > > > I would like to know why/how class A is able to access the > private field 'varB' of its inner class B. I assume that > the field 'varB's scope would be confined to that of class > B. Shouldn't the behaviour have been consistent with > trying to access the private field 'varC' of class C from > within a member function of class A? > > Thank you for your time.
B is an Inner class of A and is hence in the global scope of A.
Any declaration that is contained within another declaration (container declaration) can be accessed by the container declaration.Since B and varB are declared within A, A can access B and varB even though varB is private.
Please see the following explanation where SuN's team declaraed it as no bug and interpreted it as valid based on specification.