Inner classes¶
Definitions¶
In Java, it is possible to declare classes inside other classes. We call these classes nested classes. They can be declared as:
- static classes (so-called static nested), using the
static
keyword - non-static classes (so-called non-static or inner)
The following example shows how to define such classes in the easiest way:
public class Outer {
static class NestedStatic {
// class body
}
class Inner {
// class body
}
}
NOTE: There are two special kinds of inner classes: local classes and [anonymous_classes] (anonymous_classes.md).
Visibility¶
Non-static nested classes have direct access to the parent class, i.e. from the parent class they can use:
- fields (also static and private)
- methods (also static and private)
The following example shows these possibilities:
public class OuterClass {
private static int outerClassStaticField;
private int outerClassField;
void outerClassMethod() {
System.out.println("I am outer class method");
}
public class InnerClass {
void useOuterClassField() {
System.out.println(outerClassStaticField); // use of a static field
outerClassMethod(); // use of method
System.out.println(outerClassField); // use of private field
}
}
}
UWAGA: Unlike local classes, inner classes can use access modifiers.
NOTE: Non-static local classes cannot define static fields and methods.
In turn, the nested static classes from the parent class:
- can use static fields and methods of the parent class
- not can use non-static fields and methods
We can see these features on the next example:
public class OuterClass {
private static int outerClassStaticField;
private int outerClassField;
void outerClassMethod() {
System.out.println("I am outer class method");
}
protected static void outClassStaticMethod() {
System.out.println("I am out class static method");
}
static class InnerStaticClass {
void useOuterClassField() {
System.out.println(outerClassStaticField);
outClassStaticMethod();
//outerClassMethod(); -> compile error, we must NOT use non-static methods
}
}
}
Create internal classes¶
We will base the next examples on the following classes:
public class OuterClass {
class InnerClass {
}
static class InnerStaticClass {
}
}
To instantiate an inner non-static class, we first need to create an instance of the outer class, e.g .:
OuterClass outerClass = new OuterClass();
final OuterClass.InnerClass innerClass = outerClass.new InnerClass();
Conversely, to instantiate an inner static class, you need to access the inner class with .
, e.g .:
OuterClass.InnerStaticClass innerStaticClass = new OuterClass.InnerStaticClass();