Monday, 10 March 2014

Difference between Nested and Inner class ?


Difference between Nested and Inner class ?

A nested class is a class defined inside the definition (body) of another enclosing class.  A nested class is treated as a member of the enclosing class. 

A nested class can be of two types
- static
a) A static nested class is not very tightly integrated with the enclosing class and it lives its own independent life as well i.e., a static nested class can be instantiated like any other class from just about anywhere.
b) They are defined inside the definition of an enclosing class just to get a logical grouping of the classes, which in turn increases readability and provides better packaging convenience.
c) A static nested class can't directly access the members of the enclosing class. Like any other top-level class it needs to access the members of the enclosing class via object references only.

-  non-static
d) A non-static nested class is called an inner class and it's tightly integrated with the enclosing class unlike a static nested class.
e) An inner class instance can't exist independent to the enclosing class instance. An inner class instance always exist within the instance of the enclosing class.
f) Since, it's always associated with the enclosing class instance and it has direct access to all the members of the enclosing class - even the private members.

No comments:

Post a Comment