i was just experimenting with inner classes and came across this idea of having local yet static inner class... well i made an inner class inside a static method.. well it's just simple as that.. Here's the example i did
class Outer {
static void m() {
class LocalStatic {
void s() {
System.out.println("static local inner class method");
}
}
}
}
class Demo {
public static void main(String args[]) {
Outer.m();
}
}
This doesn't give any compile error.
I know how to access the static method m. But i want to know if there's a way to access the local class LocalStatic from an outside class.. Well as to my understanding, we can't access something inside a method right? Hence i can't access either LocalStatic or any methods or attributes inside that local class from outside of the class Outer Just wanted to make sure..
I want to know if there's a way to access the local class LocalStatic from an outside class
There isn't a way to do that. Local classes are, well, local, so the only way to access them is from the method in which the class is in scope*.
You can access objects of a local class using non-local base class or an interface:
interface SomeInterface {
void s();
}
class Outer {
static SomeInterface m() {
class LocalStatic implements SomeInterface {
public void s() {
System.out.println("static local inner class method");
}
}
return new LocalStatic();
}
}
Now you can write
SomeInterface i = Outer.m();
i.s();
* It goes without saying that there is also a way to access these classes through reflection, but that is outside capabilities of Java language itself.