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?
Security aspect. Java inner class is also very useful for providing security for an important piece of code. For instance, if an inner class is declared as private, it is unavailable to other classes which means that an object of the inner class cannot be created in any other classes.
We use inner classes to logically group classes and interfaces in one place to be more readable and maintainable. Additionally, it can access all the members of the outer class, including private data members and methods.
They're not "bad" as such. They can be subject to abuse (inner classes of inner classes, for example). As soon as my inner class spans more than a few lines, I prefer to extract it into its own class. It aids readability, and testing in some instances.
The main advantages of a nested (inner) class are: It shows a special type of relationship, in other words, it has the ability to access all the data members (data members and methods) of the main class including private. They provide easier code because it logically groups classes in only one place.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With