I encounter the following question in Java, how to initialize an instance of inner class if the inner class is declared in the method of outer class? I met an compile error in the following case. Many thanks.
class Outer {
public int a = 1;
private int b = 2;
public void method(final int c){
int d = 3;
class Inner{
private void iMethod(int e){
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("e = " + e);
}
}
}
public static void main (String[] args){
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();// there is an compile error here
}
}
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: OuterClass outerObject = new OuterClass(); OuterClass. InnerClass innerObject = outerObject.
Method-local Inner Class In Java, we can write a class within a method and this will be a local type. Like local variables, the scope of the inner class is restricted within the method. A method-local inner class can be instantiated only within the method where the inner class is defined.
Rules for Inner ClassNo inner class objects are automatically instantiated with an outer class object. If the inner class is static, then the static inner class can be instantiated without an outer class instance. Otherwise, the inner class object must be associated with an instance of the outer class.
Yes, we can access the local final variables using the method local inner class because the final variables are stored on the heap and live as long as the method local inner class object may live.
how to initialize an instance of inner class if the inner class is declared in the method of outer class?
You can't. The scope of the class is confined to the method itself. It's similar to why you can't access local variables outside the method.
From JLS §6.3 - Scope of a Declaration:
The scope of a local class declaration immediately enclosed by a block (§14.2) is the rest of the immediately enclosing block, including its own class declaration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With