static nested and non-static nested class in Java

Summary

Java's nested classes are categorized as either static or non-static, also known as inner classes. Static nested classes are accessed directly via the outer class name and can be instantiated independently, without requiring an instance of the enclosing class. Conversely, inner classes are intrinsically tied to an outer class instance, meaning an inner class object can only exist within an outer class object and gains direct access to its members. Instantiating an inner class therefore requires first creating an outer class instance, then using that instance to construct the inner class object.

Nested classes are divided into two categories: static and non-static(inner). Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes.

Static class can be defined as :

class OuterClass{
    static class StaticNestedClass{
        //OTHER STUFF
    }
}

Static nested classes are accessed using the enclosing class name:

OuterClass.StaticNestedClass

For example, to create an object for the static nested class, use this syntax:

OuterClass.StaticNestedClass nestedObject =new OuterClass.StaticNestedClass();

The creation of an instance of static nested class doesn't rely on the existence of an instance of outer class.

You can also import an static nested class when you want to create an object of nested static class easily. For example:

import OuterClass.StaticNestedClass;

StaticNestedClass staticNestedClass=new StaticNestedClass();

Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:

classOuterClass{...classInnerClass{...}}

An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.

Definition of inner class:

class OuterClass{
    sclass InnerClass{
        //OTHER STUFF
    }
}

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:

OuterClass.InnerClass innerObject = outerObject.newInnerClass();

 

JAVA STATIC NESTED CLASS INNER CLASS

  RELATED

  COMMENTS

0

No comment for this article.