Appearance
Java inner class and static nested class
In Java, an inner class is a class that is defined within another class. An inner class has access to the members (fields and methods) of the outer class, and can be used to encapsulate the implementation of a component of the outer class.
Here's an example of an inner class in Java:
java
public class OuterClass {
private int x;
public class InnerClass {
public void doSomething() {
// Access the field x of the outer class
System.out.println(x);
}
}
}To create an instance of the inner class, you need to first create an instance of the outer class, and then use the new operator to create the inner class object. For example:
java
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.doSomething();Note that outer.new InnerClass() is required because the inner class is implicitly tied to an instance of the outer class.
A static nested class is a class that is defined within another class, but is marked with the static keyword. A static nested class does not have access to the non-static members of the outer class, and can be used to encapsulate utility methods or constants that are related to the outer class.
Here's an example of a static nested class in Java:
java
public class OuterClass {
private int x;
public static class StaticNestedClass {
public void doSomething() {
// Cannot access non-static field x directly
System.out.println("Static nested class method called");
}
}
}To create an instance of the static nested class, you can use the outer class name directly, without needing an instance of the outer class:
java
OuterClass.StaticNestedClass staticInner = new OuterClass.StaticNestedClass();
staticInner.doSomething();