0

i am trying to pass method local inner class object as an argument to some other function either in the scope of outside class or out of that class

public class MethodClass {
public void p(){
    class h{
        public void h1(){
            System.out.print("Java Inner class");
        }
    }
    h h2=new h();
}
}

here h2 i want to pass to any other function in the same class MethodClass or out of that class. can any one give me the procedure to pass the argument in that way?

9
  • @satheesh: if you need the obj of a class temporarilyt to perform a service and then dispose, you can go for anonymous inner class.both method level inner class and anonymous inner class are same, except the anonymous inner has no name. Commented Mar 18, 2011 at 9:54
  • 1
    @Suresh S - that's not correct. An anonymous class is always a class that either extends another class or implements an interface. Basically, you CAN pass an anonymous inner class as the reference variable will a normal class. Commented Mar 18, 2011 at 9:57
  • @adarsh: even method level inner class can extend and implement. Commented Mar 18, 2011 at 10:03
  • @Suresh S okey your correct but that wont be useful in the context of this question Commented Mar 18, 2011 at 10:05
  • @Suresh: the only difference i can see is that , method level inner can have named constructor.otherwise both have same restriction.Also anonymous has a short syntax. Commented Mar 18, 2011 at 10:05

1 Answer 1

7

If another method needs to know about the class, then you shouldn't declare it within a method, basically. Make it a nested class within the class itself, or even a top-level class.

I can't say I've ever used method-local class declarations.

Sign up to request clarification or add additional context in comments.

4 Comments

You're right. To pass a method "local" inner class sounds like an oxymoron!
in scjp study guide it is given in Method-Local Inner Class objective --It was discussed that method local inner class cannot use local variable unless they are final because they are in stack.And when ever u tried to pass the reference to some other function they wont be alive as their scope ends with that function.so don't use local variables in side method local class....
@satheesh: What happens is that any variables captured in a class like this or an anonymous inner class are copied at the point of construction. It works fine. You just need to understand what's going on.
@MR Jon Skeet ...i didn't get u

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.