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
}
}
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.
You cannot. The Inner
class is local to the method(int)
method.
If you want to access it, you will need to declare it in a larger scope.
In a sick twist of fate, you can use reflection to get an instance. Take for example
package com.so.examples;
class Main {
public void method(final int c){
class Inner{
public Inner() {}
private void iMethod(int e){
System.out.println("inner method");
}
}
}
public static void main (String[] args) throws Exception{
Class clazz = Class.forName("com.so.examples.Main$1Inner");
Constructor<?> constructor = clazz.getConstructor(new Class[]{Main.class});
Object instance = constructor.newInstance(new Main());
System.out.println(instance.getClass());
}
}
This prints out
class com.so.examples.Main$1Inner
Without reflection, you cannot access any of its members because you cannot declare a variable of type Inner
outside of the method.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.