Friday, 25 April 2014

nested classes in java

Defination
class declared inside a class is known as nested class.

Syntax

Class Outer_Class_Name{
...
...
   Class Inner_Class_Name{
   ...
   ...
   }
}

Types of nested classes
There are two types of nested classes non-static inner classes and static nested classes.
  1. non-static nested class(inner class)
    • a)Member inner class
    • b)Annomynous inner class
    • c)Local inner class
  2. static nested class


Difference between non-static inner classes and static nested classes in Java?

Non-static inner classes  have access to other members of the enclosing class, even if they are declared private. 
Static nested classes do not have access to other members of the enclosing class.

Difference between narmal classes and  nested classes in Java?

A nested class is a member of its enclosing class.
As a member of the OuterClass, a nested class can be declared privatepublicprotected, or package private
(Recall that outer classes can only be declared public or package private.)

Advantage of nested classes?

Why Use Nested Classes?

Compelling reasons for using nested classes include the following:
  • It is a way of logically grouping classes that are only used in one place: If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.
  • It increases encapsulation: Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declaredprivate. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.
  • It can lead to more readable and maintainable code: Nesting small classes within top-level classes places the code closer to where it is used.


static nested class

A static class that is created inside a class is known as static nested class.
  • It can access static data members of outer class including private.
  • It cannot refer directly to instance variables or methods defined in its enclosing class: it can use them only through an object reference.
  • static nested class cannot access non-static (instance) data members directly.