Akash Thakare
Akash Thakare

Reputation: 23012

Class Inside Method

public class Demo 
{

    public void met(Object d)
    {

        class my {
            public String Work(String s){
                return s+",JAVA";
            }
        }
        d=new my().Work("Hello");//statement 1
        System.out.println(d);//statement 2

    }

    public static void main(String args[])
    {
        new Demo().met(new Object());
    }

}

I don't know it's asked before or not. Here in this class Demo I am creating class my.

When I put statement 1 and 2 before class it gives me error but when I put it after class that's okay.

So it means when I call method, class is loaded and class file is created named Demo$1my.class so that if I put statement 1 and 2 after class it works. Is it So?

My Question is can I create object of my class from main method and How?

Upvotes: 3

Views: 684

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503469

can I create object of my class from main method and How?

No. Only the met method knows anything about the class. If you want to use the class outside that method, you should declare it either as a nested class within Demo, or as a completely separate non-nested class.

Personally I would try to avoid nested classes as far as possible - they have odd restrictions, you can often end up creating inner classes instead of nested classes by accidentally forgetting the static modifier, and they're generally a pain.

Upvotes: 3

Related Questions