Nested Classes

Java allows us to define classes inside other classes. Nested classes enable us to logically group classes that are only used in one place, write more readable and maintainable code & increase encapsulation.

Several types of nested classes available in language:-

  • Static Nested classes
  • Non- static Nested classes
  • Local classes
  • Anonymous classes

The scope ofnested classes is bounded by the scope of its enclosing class. Nested class doesn't exist independently of class outer class.

A Nested class has access to members, including private members of class in which it is nested. However, reverse is not true i.e, the enclosing class does not have access to members of nested class.

A Nested class is also a member of its enclosing class, a nested class can be declared private, public, protected or package private (default).

Syntax of Nested Classes

You use nested class to reflect and to enforce relationship bet5wen two classes. you should define a class within another class when the nesred class makes sense only in the context of its enclosing class or when it relies on enclosing class of its function.
For Example:- A text cursor might make sense only in context of a text component.

As a member of enclosing class, it has unlimited access to its enclosing class's members, even if they all declared private. It is fully consistent with the meaning of private and other access specifiers. The Access Specifiers restrict access to members for classes outside enclosing class. Nested class is inside its enclosing class so that it has access to enclosing class's members.

As with instance methods & variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's instance variables and methods. Also, because an inner class is associatd with an instance. it cannot define any static members itself.

Diffrentiate Nested & Inner Class

The term nested class reflects the syantactic relationship between two classes. i.e. the code for one class appears within the code of another.
The term inner class reflects re3lationship between objects are instances of two classes.The instance of inner class can exist only within an instance of enclosing class and has direct baccess to instance variables and methods of its enclosing instance.

Syntax of Nested Classes

Member functions of a nested class follow regular access rules and have no special access privilages to members of their enclosing classes. Member functions of enclosing class have no special access to members of nested class.
You can define member functions and static data members of nsted class in namespace.

Why Nested Class?

It is a way of logically grouping classesthat are only used in one place. If a class is useful to only one other class, then it is logically to embed it in that class and keep two together.

Nesting such "helper classes" makes pacxkage more .......?.


Increase Encapsulation:- consider two top level classes A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A. A's member can be declared private and B can access them.

Static Nested Class

If a nested class, has static modifier applied in it, then it is called static nested class. As due to this, static nested class can access only static members of its outer class. i.e., it cannot refer to non-static member of its enclosing class directly. It can use them only through an object refrence. Due to this restriction, static nested class is rarely used.
Static nested classes are accessed using the enclosing class name:
OuterClass.StaticNestedClass

to create an object for static nested class.
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

Key points of static Nested Classes:-
  • They only have access to static members in enclosing class.
  • As with static members, these belongs to their enclosing class and not to a instance a class.
  • They can have all types of access modifiers in their declarations.
  • They can define both static and non-static members.
Implementation:
class OuterClass{
    static int outerx = 10;
    int outery = 20;
    private static int outerprivate = 30;
    
    static class staticNestedClass
    {
        void display()
        {
            System.out.println("Outer x="+outerx);
            System.out.println("Outer private= "+outerprivate);
        }
    }
}
public class staticNestedClassDemo
{
    public static void main(String args[])
    {
        OuterClass.staticNestedClass nestedObject= new OuterClass.staticNestedClass();
        nestedObject.display();
    }
}
          Output:
                 Outer x=10
                 Outer private= 30
          

Non - Static Nested Classes

  • Also known as inner class.
  • It has access to all variables and methods of outer class including its private data members and methods and may refer to them directly. But reverse is not there. Outer class cannot directly access members of inner class. Inner class can be declared private, public, protected or with default access whereas an outer class can have only public or default access.
  • This class can be created only with in the scope of outer class. Java compiler generates an error if any code outside outer class attempts to instantiate inner class directly.
  • They can only define non-static members.
Implementation:
class Outer{
    public void display()
    {
        Inner in = new Inner();
        in.show();
    }
    class Inner
    {
        public void show()
        {
            System.out.println("Inner Class");
        }
    }
    
}
public Test
{
    public static void main(String args[])
    {
        Outer ot= new Outer();
        ot.display();
    }
}
          Output:
                Inner Class
          

Local Classes

This is a special type of inner class, in which the class in defined inside a method or scope block.

  • They cannot have access modifiers in their declarations.
  • They have access to both static & non-static members in enclosing context.
  • They can only define instance members.

Implementation:
public class BCE{
    void Bti()
    {
         class Local
        {
            void run()
            {
                System.out.println("Inner run Method");
            }
        }
        Local local = new Local();
        local.run();
    }
    public static void main(String args[])
    {
        BCE bce = new BCE();
        bce.Bti();
    }
}
          Output:
                Inner run Method
          

Anonymous Classes

Can be used to define an implementation of an iterface or an abstract class without having to create a resuable implemetation. Key Points:-

  • Cannot have access modifiers.
  • Access to both static and non-static members in enclosing context.
  • They can only define instance members.
  • They are the only type of nested classes that cannot define constructors or extend other classes or interfaces.

Implementation:
interface Anonymous
{
    void type()
    {
        public class Atest
        {
            public static void main(String args[])
            {
                Anonymous an = new Anonymous()
                {
                    public void type()
                    {
                        System.out.println("Anonymous Class");
                    }
                };
                an.type();
                
            }
        }
    }
}
          Output:
                Anonymous Class
          

About the Author
Rajesh K. Bansal (SCJP-Sun Certified Java Programmer)
17 Years experience in Training & Development. Founder of realJavaOnline.com, loves coding in Java(J2SE, J2EE), C++,PHP, Python, AngularJS, Android. If you like tutorials and want to know more in depth about Java , buy his book "Real Java" available on amazon.in.
#Email : [email protected] #Contact : 98722-46056
Available on Amazon
Card image cap
Under the guidance of Founder & Author of "realJavaOnline.com". M:9872246056
Card image cap