Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java compiled classes contain dollar signs

I've been using Eclipse as my IDE. I also use it to export my application into a JAR file. When I look at my classes in the JAR file, a few of my classes contain the name of that class, a dollar sign, then a number. For example:

Find$1.class  Find$2.class Find$3.class Find.class 

I've noticed it does this on bigger classes. Is this because the classes get so big, it compiles it into multiple classes? I've googled and looked on multiple forums, and search the Java documentation but have not found anything even related to it. Could someone explain?

like image 919
Frizinator Avatar asked Jul 09 '12 03:07

Frizinator


People also ask

Can Java use dollar in class name?

Second, '$' is used as a separator character for the Java compiler to specify when a class is declared under another class. For instance, an inner class named Foo inside Bar would be 'Bar$Foo. class' when compiled, and an anonymous class inside Bar would be 'Bar$1.

What is $$ in Java?

So $ is used to separate names for inner classes, and $$ marks lambda-expression-based inner classes.

What is $1 class file in Java?

The $1 are anonymous inner classes you defined in your WelcomeApplet. java file. e.g. compiling public class Run { public static void main(String[] args) { System.out.println(new Object() { public String toString() { return "77"; } }); } private class innerNamed { } }

What should be the name of class in Java?

Class names should be nouns, in mixed case with the first letter of each internal word capitalized. Try to keep your class names simple and descriptive. Use whole words-avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML).


2 Answers

Inner classes, if any present in your class, will be compiled and the class file will be ClassName$InnerClassName. In case of Anonymous inner classes, it will appear as numbers. Size of the Class (Java Code) doesn't lead to generation of multiple classes.

E.g. given this piece of code:

public class TestInnerOuterClass {     class TestInnerChild{      }      Serializable annoymousTest = new Serializable() {     }; } 

Classes which will be generated will be:

  1. TestInnerOuterClass.class
  2. TestInnerOuterClass$TestInnerChild.class
  3. TestInnerOuterCasss$1.class

Update:

Using anonymous class is not considered a bad practice ,it just depends on the usage.

Check this discussion on SO

like image 199
mprabhat Avatar answered Oct 06 '22 17:10

mprabhat


This is because you have anonymous classes within this larger class. They get compiled using this naming convention.

See The Anonymous Class Conundrum

like image 43
jjathman Avatar answered Oct 06 '22 17:10

jjathman