Are Inner Classes lightweight?

后端 未结 3 2018
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-02 12:43

Are inner classes more lightweight than normal classes, or in the end java compiles inner classes just like normal classes?

I know classes in java are not all very l

3条回答
  •  滥情空心
    2021-01-02 13:36

    Inner classes and anonymous inner classes both compile down to .class files. For example:

    class Outer {
         class Inner {
    
         }
    
         Object function() {
              return new Object() {
    
              };
         }
    }
    

    Will generate three .class files, Outer.class, Outer$Inner.class, and Outer$1.class. They aren't more "lightweight" than other classes, and (to the best of my knowledge) there's no advantage to using one over the other from a performance perspective. Of course, inner classes and especially anonymous inner classes are really useful in contexts where regular classes are harder to code, but that's a separate issue.

提交回复
热议问题