Skip to main content

Java: what is Nested Classes?

What are Nested classes? What are Types of nested class? to know that read the following correctly and completely.

NESTED CLASSES.

In java , just like methods, variable of a class too can have another as its member writing a class within another is allowed in java.

The class written within is called the nested class. and the class that holds the inner class is called the outer class.

Syntax.
class OuterClass
{
  //Dater member.
  //Member methods
  class InnerClass
  {
    //data members.
   //member methods
  }
}

Nested classes are divided into two types:
  • Non-static nested classes
  • Static nested classes.


Non-static nested classes(Inner Classes).

Inner classes are a security mechanism in java. We know a class cannot be associated with the access modifier private. but when we have class as a member of another class, then the inner class can be made private.

They are further divided into 3 types.
  • Inner class.
  • Method-local inner class.
  • Anonymous inner class.

Inner class.
This is quite simple. You just need to write a class within a class. It cannot be accessed from an object outside the class.

Method-local inner class.
In java, we can write a class within a method and this will be a local type. and it is restricted within the method.

A method -local inner class can be instantiated only with in the method where the inner class is defined.

Anonymous inner class.
An inner class declared without a class name is known as an anonymous inner class.

In case of anonymous inner classes, we declared and instantiate them at the same time.


Static Nested Class.

A static inner class is a nested class which is a static member of the outer class.

It can be accessed without instantiating the outer class, using other static members. 

Just like static members,a static nested class does not have access to the instance variable and methods of the outer class.

Syntax:
class MyOuter
 {
            //Data members
           //Member method.
     static class Nested_demo
    {
      //data members
      //member methods
     }
}

Comments