|
|
Overloading, Overriding, Runtime Types and Object Orientation - Static Nested Classes
- a static inner class behaves like any top-level class except that its name and accessibility are defined by its enclosing class (JPL pg 50) ie use new Outer.Inner() when calling from another class
- formally called top-level nested classes (JPL pg 50)
| Note |
There is alot of confusion over the terminology involving 'static nested classes'. They are not inner classes!
While the formal name, as stated in the
Java Programming Language, Second Edition
by Ken Arnold and James Gosling, is 'top-level nested', it is a bit of an oxymoron.
Joshua Bloch, author of Effective Java,
prefers the term 'static member class' which provides a clearer sense of how such classes are utilized.
|
class Outer {
public static void main(String[] args) {
int x = Inner.value;
}
static class Inner {
static int value = 100;
}
}
- they are not associated with an instance of their outer class ie you can create an Inner class object from within the Outer class using new Inner(); you do not need to create an Outer class object first as is required with non-static inner classes
- static inner classes can directly access static fields of the outer class but must use an instance of the outer class to access the outer classes instance fields
Example Code
|