3
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?

Maroun
  • 94,125
  • 30
  • 188
  • 241
akash
  • 22,664
  • 11
  • 59
  • 87
  • Your naming conventions are confusing.. – Maroun Mar 25 '14 at 08:03
  • possible duplicate of [Use of class definitions inside a method in Java](http://stackoverflow.com/questions/2428186/use-of-class-definitions-inside-a-method-in-java) – Djizeus Mar 25 '14 at 08:05

1 Answers1

3

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 2
    Why would someone have a class *inside* a method? Specially when it's not *anonymous*.. – Maroun Mar 25 '14 at 08:05
  • 2
    @MarounMaroun: I've used it precisely *once* that I can remember- when I wanted to declare a specific exception which I then used in a callback, and then catch that particular exception. – Jon Skeet Mar 25 '14 at 08:06
  • I'm just curious, why didn't you declare the class *outside* the method? Can you please post a small example of that? I really want to know when it's better to have a class *inside* a method. – Maroun Mar 25 '14 at 08:09
  • 2
    @MarounMaroun: I didn't want any other code to know about the class, basically. There's no reason any other class would *need* to know about the class. – Jon Skeet Mar 25 '14 at 08:11