What is the use of an inner class in a Java server side application? Please explain the benefits other than Swing component containment hierarchy using inner class.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The benefits of anonymous inner classes are exactly the same as for Swing; i.e. they allow you to implement callbacks without the “programming overhead” of separate class file.
Of course, this is all syntactic sugar. The compiled code for (and performance of) the two approaches are pretty much the same. Indeed, the JVM makes no real distinction between regular and inner / nested classes.
All of the inner/outer scoping stuff is resolved at compile time and translated into a hidden constructor parameter and a hidden variable in the inner instance that refers to the outer instance. You can simulate this all yourself in non-nested classes by coding explicit parameters / variables. Hence it is syntactic sugar.
The only thing that you can do with inner classes that you cannot do with separate classes is access private members. To achieve this using separate classes you would need to change the relevant private members to package private. But I’d still classify that as syntactic sugar … or close enough.