Salvadora
Salvadora

Reputation: 379

One Java File, but two classes

I have in my project a few classes. After compiling I find for two java-Files to classes for each: name.class and name$.class. What can be the reason for that? I see nothing special about the classes.

Greetings

Upvotes: 1

Views: 1808

Answers (4)

kamituel
kamituel

Reputation: 35950

It is an anonymous inner class, like on example:

new Runnable() { ... }

Edit: some valid points from the comments:

  • enum types are also compiled to a separate class files (as these are in fact classes)
  • anonymous inner classes are numbered sequentially (MyClass$1.class, MyClass$2.class, etc.)
  • unanymous inner classes are named (ex. MyClass$InnerNamedClass.class)

Upvotes: 7

Boris the Spider
Boris the Spider

Reputation: 61128

Inner classes in Java are compiled to Class$InnerClass.

If you have named classes then the name of the class is used. If the class in anonymous, i.e. you have something like:

final ActionListener actionListener = new ActionListener() {

    public void actionPerformed(ActionEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
};

Then numbers are used, so this would be Class$1.

Upvotes: 0

DiogoSantana
DiogoSantana

Reputation: 2434

Java compile creates a .class file to every class defined on the .java file. You should have a anonymous inner class like this:

button.addListener(new PressListener() {
    public void onPressed(Event event) {
        System.out.print("test");
    }
});

Upvotes: 0

rgettman
rgettman

Reputation: 178253

You have an inner class (anonymous or named) in your public class. This behavior is normal; the Java compiler will produce one .class file for every class, no matter how many classes are defined in a source file.

Upvotes: 2

Related Questions