Wednesday, December 10, 2008

Inner Classes

Q1:

When you create an inner class, an object of that inner class has a link to the enclosing object that made it, and so it can access the members of that enclosing object -- without any special qualifications. In addition, inner classes have access rights to all the elements in the enclosing class.

How to understand this paragraph?

Answer: The inner class secretly captures a reference to the particular object of the enclosing class that was responsible for creating it. Then, when you refer to a member of the enclosing class, that reference is used to select that member. Construction of the inner-class object requires the reference to the object of the enclosing class, and the compiler will complain if it cannot access that reference. Most of the time this occurs without any intervention on the part of the programmer.

Q2. Does an outer class have access to the private elements of its inner class?

Seems the answer is yes from the result of my little test code. But why?

Q3.
If you're defining an anonymous inner class and want to use an object that's defined outside the anonymous inner class, the compiler requires that the argument reference be final. If you forget, you'll get a compile-time error message. Why?

No comments: