Saturday, October 25, 2014

What is Nested class or Inner class ?


Defining a class within another class is called Nested / Inner class.
Nested classes are divided into 2 Categories,
  • static
  • non-static

Eg: 

class OuterClass {
    ...
    static class StaticNestedClass {
        ...
    }
    class InnerClass {
        ...
    }
  • Nested class is a member of it's outer or enclosing class.
  • non-static nested classes have access to other members of the enclosing class, even they are declared as 'private'.
  • static nested classes do not have access to other members of the enclosing class.
  • As a member of outer class a nested class can be declared private,public and protected or package-private(if a class has no modifier it is visible within own package, this is also known as package-private).
Uses of nested classes:
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 classes together.Nesting such 'helper classes' makes their package streamlined. 
It Increases Encapsulation: Consider there are two high-level classes A,B. Where B needs access to members of A. 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 outside world.
It can lead more reliable and maintainable code: nesting small classes within Top-Level classes places the code closer to where it used.
static nested classes:
  • Like static class methods, a static nested class can not refer directly to instance variables or methods defined in it's enclosing class.It can use them only through an object reference.
  • In java we can not make Top level class as static, only nested classes can be static.
  • An instance of inner class can not be created without an instance of outer class.
  • static nested classes are accessed using the enclosing class name.
                       OuterClass.StaticNestedClass
    To create an object for static nested class
          OuterClass.StaticNestedClass  staticnestedclsobj=new 
OuterClass.StaticNestedClass();
To Create Object for non-static inner class
OuterClass.NestedClass nestedclsobj=new OuterClass().new NestedClass();

0 comments:

Post a Comment