Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Inner Classes lightweight?

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?

like image 594
Waneck Avatar asked Jan 27 '11 03:01

Waneck


People also ask

Is it good to use inner class?

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.

What is the purpose of inner 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.

Is nested classes bad?

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.

What are the advantages of Java inner classes?

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.


1 Answers

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.

like image 79
templatetypedef Avatar answered Sep 22 '22 06:09

templatetypedef