Execute main method inside inner class

If your .java file have inner/nested classes, post compilation those are generated as TheClass$xxx.class files by the compiler.

See this:

Inner class definitions produce additional class files. These class files have names combining the inner and outer class names, such as MyClass$MyInnerClass.class.

So you should do: java A$B.


Its just like simple class. Run command java A$B When inner class is compiled, it is prepended with outer class name In this case you two class files. i.e . A.class and A$B.class

  • java command takes the classname as the argument and not the filename
  • So simple command java A$B will do the work
  • If you have anonymous classes then the classnames will be like OuterClass$1, OuterClass$1 and so on.

So if you modify your example as follows, now including anonymous and method local inner classes

import java.io.Serializable;

public class A {
    static class B {
        public static void main(String[] args) {
            System.out.println("Done");
            Serializable obj = new Serializable() {
            };
            Serializable obj1 = new Serializable() {
            };
            class MethodLocalClass {
            }                                           
        }
    }
}

Then the class files you will get are A.class, A$B.class, A$B$1.class, A$B$2.class for the anonymous classes and A$B$1MethodLocalClass.class.

Hope this example helps a bit :)


Try something like this:

  java A$B

Update according to comments:

In linux shell you should escape $. So the command became:

java 'A$B'