One Java File, but two classes

北城余情 提交于 2019-12-04 05:32:50

问题


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


回答1:


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)



回答2:


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.




回答3:


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");
    }
});



回答4:


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.



来源:https://stackoverflow.com/questions/15670878/one-java-file-but-two-classes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!