|
This chapter partially covers two SCJP objectives, specifically sections 1.2,4.1 and 6.3. We learned why nested classes are declared, how they are declared and constructed. We also learned the different types of nested classes, their accessibility and behavior. Here is a brief summary of the important concepts learned in this chapter.
Any class declared within a body of another class or an interface
is called as a nested class.
An inner class is a type of nested class that is not explicitly
declared as static.
Nested
classes are categorized based on where they are declared
within a class body as:
§ Member Classes
Non-static member inner class
Static nested class
Local inner Class
Anonymous inner class
Non-static member class
§ A non-static member class is declared inside a class body just like the other members of that class.
§ Member inner class can be public, private, protected or with (default) access.
§ Member inner class can access all the member variables of the enclosing class.
§ To instantiate a member inner class an instance of the enclosing class must be created first.
Static nested class
§ Static nested classes are member classes with static modifier.
§ Static nested class has access to only static member variables and static methods of the outer class.
§ It does not need an instance of the enclosing class for its instantiation. It is accessed just like any other static feature of a class.
§ A static nested class is not an inner class but a top-level nested class.
Local inner class
§ Local class declaration may be contained by a block or a method body.
§ The scope of a local class declared in a block is within the rest of the block.
§ Local class can be declared as abstract or final.
§ Method-local class is useful only if it is instantiated within the method body.
§ Method-local class can be instantiated only after its declaration in the method body.
§ Local class defined in a method has access to only the final method variables and to the enclosing class's member variables.
Anonymous inner class
§ Anonymous inner class does not have name.
§ It can either extend a class or implement an interface but cannot do both at the same time.
§ Anonymous inner class cannot implement multiple interfaces.
§ The definition, construction and first use of anonymous class happen at same place.
§ Anonymous class does not have any constructor of its own for but it can call the constructor of its super class.
§ An anonymous class can never be declared as abstract or static.
§ An anonymous class is always implicitly final.
§ Anonymous class defined in a method has access to final method variables and to the outer class's member variables.