Chapter8
Un article de Sometimes Kitties Think Too.
Sommaire |
[modifier]
Chapter 8 - "Inner Classes"
[modifier]
Types of Innner Classes
1) regular inner class
2) method-local inner class
3) anonymous
+ subclass
+ implementor
4) static nested class
[modifier]
Rules
- Regular inner classes cannot have static declarations. Must have an instance of the outer class.
- Modifiers
You can use the same modifiers for inner classes that you use for other members of the outer class. For example, you can use the access specifiers — private, public, and protected — to restrict access to inner classes, just as you do to other class members.
[modifier]
Constructing Inner Classes
[modifier]
Non-static Inner Class (Nested)
| class OuterClass { |
| ... |
| static class StaticNestedClass { |
| ... |
| } |
| class Non-StaticInnerClass { |
| ... |
| } |
| } |
- non-static method constructing an instance of the nested class:
Inner x = new Inner();
- Syntax for instantiating an inner class externally:
new MyOuter().new MyInner()
- How to construct an instance on a nested class where either no "this" object exists, or the current this object is not an instance of the outer class:
Outer.Inner y = new Outer().new Inner();
OR
Outer x = new Outer();
Outer.Inner y = x.new Inner();
- How to create an instance of a static inner class
Outer.Inner I = new Outer.Inner();
- Regular Inner classes are scoped at the same level as instance variables
- Inner classes have access to member variables and methods of the containing class
[modifier]
Method Local Inner Classes
- In addition, Method-local inner classes cannot use the local variables of the method that the inner class is in. Only if they are declared /final/
- Must instantiate an inner class within the method below the definition if you want to use it.
- All modifiers apply to inner and method-local inner classes (abstract, final, private ...)
[modifier]
Anonymous Inner Classes
- Anonymous classes are either subclasses or implementors
- Anonymous classes do not inherit the superclass methods that they do no override
- Inner classes can access all members of the outer class, even the "private" ones
Except static nested classes do no have access to non-static methods/variables of the outer class
- anonymous inner classes do not have constructors
class ThisIsAnAnonymousClass {
void f() {
System.out.println("F method");
}
void g() {
System.out.println("G method");
}
}
.....in another class.....
inner.classMethod(new ThisIsAnAnonymousClass()
{
void f()
{
System.out.println("I'm doing my own thing!");
}
}
);
| Type | Scope | Inner |
|---|---|---|
| static nested | member | no |
| inner (non-static) | member | yes |
| method local | local | yes |
| anonymous | only where defined | yes |
~
