04-12-2012, 04:24 PM
Advanced Java Programming
Advanced Java Programming.pdf (Size: 854.84 KB / Downloads: 50)
Introduction
• JDK 1.1 introduced the key-concept of inner class
• An inner class is a class whose declaration appear within:
• class declarations
• method bodies
• expressions
• The aim is in enforcing the encapsulation providing a clean
way for structuring classes within a package. . .
• . . .we’ll see what it means in a moment!
Basic Definitions
The Scope of a class
• A class is associated to an enclosing scope which can be
• a package if the class is a toplevel class
• a class/method declaration if the class is an inner class
Member Inner Classes
• Hiding implementation details (private fields of a MI are
only accessible from the enclosing class’ scope)
• Expressing dependency beetween inner/enclosing class
instances (e.g a FixedStackEnum iterates over a given
FixedStack instance)
Translating Inner Classes into Toplevel Classes
Inner classes as toplevel classes
• When compiling the example two classfiles are generated:
• FixedStack.class
• FixedStack$FixedStackEnum.class
• Pay attention at how inner class names are encoded using ’$’
• And AI names? And name-clashing?
Accessing the enclosing instance
• The this$0 field is added by the compiler to the translated
class FixedStack$FixedStackEnum
• This way translated inner classes can still access fields of their
enclosing instances (e.g. this$0.top)
• What if the field to be accessed is private?