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 lightweight themselves, and they occupy part of the permgen memory, so I'd like to know if it's best to use closure-like functions as inner classes, or if standard classes would also do fine?
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.