Search code examples
javaclassobjecttheoryscjp

Java. Method Inner Object as return type


Can I return method local inner object from method?

public class myClass {
    public MyMethodInnerClass getMethodInnerClassObject() {
        class MyMethodInnerClass {
        }
        
        MyMethodInnerClass myMethodClass = new MyMethodInnerClass();
        
        return myMethodClass;
    }
}

throws compilation error. If I can't return my method-local inner class object, then how can I save it after the method returns? How can I reference this object for future usage?


Exception thrown:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: MethodInnerClass cannot be resolved to a type

And also, I'm aware, that local variables in method are stored in stack and deleted just after the method exists.


Solution

  • The scope of your class is inside the method only. You can do this however

    public Object getMethodInnerClassObject() {
    

    or

    static class MyMethodInnerClass { }
    
    public MyMethodInnerClass getMethodInnerClassObject() {
        return new MyMethodInnerClass();
    }