18

If I have an inner class, like this:

public class Test
{
    public class Inner
    {
        // code ...
    }

    public static void main(String[] args)
    {
        // code ...
    }
}

When I compile it, I expect it should generate two files:

Test.class
Test$Inner.class

So why do I sometimes see classfiles like SomeClass$1.class, even though SomeClass does not contain an inner class called "1"?

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Johan
  • 1,940
  • 1
  • 13
  • 18
  • Can you clarify why you did not see Test.class and Test$Inner.class? I assume there another SomeClass in the same package that generated the class files you did see? – Miserable Variable Dec 19 '08 at 10:35

3 Answers3

23

The SomeClass$1.class represent anonymous inner class

hava a look at the anonymous inner class section here

hhafez
  • 38,949
  • 39
  • 113
  • 143
  • 1
    Note that the names of inner classes are not specified so they need not be of this form and it would be a bug to rely on that. But that being said, I've not yet seen a compiler that generates different names. – Joachim Sauer Dec 19 '08 at 09:49
9

You'll also get something like SomeClass$1.class if your class contains a private inner class (not anonymous) but you instantiate it at some point in the parent class.

For example:

public class Person {

    private class Brain{
        void ponderLife() {
            System.out.println("The meaning of life is...");
        }
    }

    Person() {
        Brain b = new Brain();
        b.ponderLife();
    }
}

This would yield:

Person.class
Person$Brain.class
Person$1.class

Personally I think that's a bit easier to read than a typical anonymous class especially when implementing a simple interface or an abstract class that only serves to be passed into another local object.

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
waltwood
  • 955
  • 2
  • 9
  • 12
  • 1
    Why does javac do this? This case is more explicitly asked at: http://stackoverflow.com/questions/2883181/why-is-an-anonymous-inner-class-containing-nothing-generated-from-this-code – Ciro Santilli OurBigBook.com Apr 07 '15 at 21:13
3

to build up on hhafez : SomeClass$1.class represents anonymous inner classes. An example of such a class would be

public class Foo{
  public void printMe(){
    System.out.println("redefine me!");
  }
}


public class Bar {
    public void printMe() {
    Foo f = new Foo() {
        public void printMe() {
        System.out.println("defined");
        }
    };
    f.printMe();
    }
}

From a normal Main, if you called new Bar().printMe it would print "defined" and in the compilation directory you will find Bar1.class

this section in the above code :

    Foo f = new Foo() {
        public void printMe() {
        System.out.println("defined");
        }
    };

is called an anonymous inner class.

Jean
  • 21,329
  • 5
  • 46
  • 64