0

I am not getting the need of inner classes. can anybody give scenario and reasons. What exactly the inner class is differ from another class.

user3516780
  • 149
  • 1
  • 1
  • 5
  • you use for `singleton object` using `inner class` for further reference use (http://docs.oracle.com/javase/tutorial/java/javaOO/whentouse.html) – Bhargav Modi Dec 18 '14 at 06:00
  • Did you check the [docs](http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html)? – TheLostMind Dec 18 '14 at 06:06

2 Answers2

2

From javadocs

Use a non-static nested class (or inner class) if you require access to an enclosing instance's non-public fields and methods. Use a static nested class if you don't require this access.

For example you want to create a class which is closely tied to another class and might only be used by that class, then it makes sense to make it as inner class of that class, instead of creating a seprate class file for it. Also inner class give access to the enclosing class's private fields , which can be useful if you want to use them in only one class and make private for everything else, then you can make that class as inner.

Mustafa sabir
  • 4,130
  • 1
  • 19
  • 28
0

There are basically three reasons of inner classes in java. They are as follows:

1) Inner classes represent a special type of relationship that is it can access all the members (data members and methods) of outer class including private.

2) Inner classes are used to develop more readable and maintainable code because it logically group classes and interfaces in one place only.

3) Code Optimization: It requires less code to write.

Explanation :

Inner classes can be used in multi-thread programming as explained by BalaYesu and you can better understand this with the example of a chat engine in which you press the “Enter” or “Return” key on your keyboard to send your message. So, the “Enter” key could be considered one event that triggers a call to one of the methods for sending message. And, if our chat client class wants to detect if someone is typing in a window, then clearly the event that would trigger the call is someone typing – so we would need some code to detect when someone is actually typing in a window in real time – basically when they are pressing a button inside their chat window. This is why inner classes were created. An instance of an inner class can access members of an instance of the outer class, because an inner class is just another member of the outer class. And, inner classes can even access the private members of the outer class

References :- Inner Classes Explained & Inner Classes

OshoParth
  • 1,492
  • 2
  • 20
  • 44