uses of instantiate member inner class
To instantiate a member inner class in Java, you first need to instantiate the outer class, and then use that instance to create an instance of the inner class. Here’s the general syntax:
Table of Contents
```java
OuterClass outerObject = new OuterClass();
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
```
Here’s a breakdown of the steps:
1. Instantiate the Outer Class:
Create an instance of the outer class using its constructor.
2. Instantiate the Inner Class:
Use the instance of the outer class to create an instance of the inner class using the `new` keyword, followed by the inner class name.
Here’s an example demonstrating how to instantiate a member inner class:
```java
public class OuterClass {
private int outerField;
// Member inner class
public class InnerClass {
private int innerField;
public void innerMethod() {
System.out.println("Inner method of InnerClass");
}
}
public static void main(String[] args) {
// Instantiate the outer class
OuterClass outerObj = new OuterClass();
// Instantiate the inner class using the outer class instance
OuterClass.InnerClass innerObj = outerObj.new InnerClass();
// Accessing the inner class method
innerObj.innerMethod();
}
}
```
In this example, `OuterClass` is the outer class containing the member inner class `InnerClass`. We first instantiate an instance of `OuterClass` using its constructor `new OuterClass()`. Then, we create an instance of `InnerClass` using the syntax `outerObj.new InnerClass()`. Finally, we can access methods and fields of the inner class through this instance.