Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple .class files generated for a class?

Tags:

java

class

javac

Out of curiosity, why are sometimes multiple Java .class files generated for a class after compilation? For example, my application has six classes. For one class, a total of 10 .class files has been generated, starting from MyClass#1 up to MyClass#10.

like image 813
Ariod Avatar asked Jun 23 '09 11:06

Ariod


3 Answers

These are for inner classes and static nested classes. The ones with numbers are anonymous inner classes.

For example:


class Foo {
   class Bar { }
   static class Baz { }
   void run() {
      Helper t = new Helper() {
         int helpMethod() {
            return 2;
         }
      };
    }
}

This will produce class files Foo.class, Foo$Bar.class, Foo$Baz.class and Foo$1.class (for the implementation of the Helper interface)

like image 146
Simon Nickerson Avatar answered Nov 16 '22 16:11

Simon Nickerson


You get more .class fils from a single source file if

  • the class contains inner classes or static inner classes. Inner classes can nest. Their names are <outer class name>$<inner class name>.

  • inner interfaces which are always static.

  • anonymous inner classes (which in fact are plain inner classes without a name)

  • package access interfaces and classes before and after your main class. You can have an arbitrary number of package access classes and interfaces in a single Java source file. Usually small helper objects that are only used by the class are just put into the same file.

like image 20
Peter Kofler Avatar answered Nov 16 '22 16:11

Peter Kofler


One java source file can generate multiple class files, if your class contains inner classes. Anonymous inner classes are represented by your numbered class files.

like image 4
skaffman Avatar answered Nov 16 '22 14:11

skaffman