This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Please UseCodeTags when posting code or configuration. Unformatted code and configuration is very difficult to read. You can edit your post to include them by using the button.
Inner classes might be used where only the containing class cares about their definition/implementation. Anonymous inner classes can be used for one-off implementations, used to create closures, and so on.
Joined: Jan 21, 2010
Here my sample innerclass code :
And here my top level class code goes :
My question is Which one is better code when compare with JVM?
Why we are coming to inner class even we can do the same program without using innerclass?
Please help me friends.
Before addressing your question, first we should address below questions.
1. Is my class have more responsibilities (violating single responsibility principle)?
2. If yes, are the responsibilities private to my class ?
If the responsibilities are private to the class, then separate the extra responsibility from the outer class and put it in the nested/inner class.
Why and when to use nested/inner classes ?
1. Use nested/inner classes for better organization of the class, but don't overuse it.
2. If your class has an extra responsibility and if the scope is within the class, then go ahead and use nested/inner classes.
3. Writing a method adds a behavior to the outer class and writing a nested/inner class makes your outer class think about its own responsibility.
4. You gain all the advantages of OOP using inner classes where necessary.