![]() |
VOOZH | about |
In Java, it is possible to define a class within another class, such classes are known as nested classes. They enable you to logically group classes that are only used in one place, thus this increases the use of encapsulation and creates more readable and maintainable code.
Syntax:
class OuterClass
{
...
class NestedClass
{
...
}
}
In the case of normal or regular inner classes, without an outer class object existing, there cannot be an inner class object. i.e., an object of the inner class is always strongly associated with an outer class object. But in the case of static nested class, Without an outer class object existing, there may be a static nested class object. i.e., an object of a static nested class is not strongly associated with the outer class object. As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class: it can use them only through an object reference. They are accessed using the enclosing class name.
OuterClass.StaticNestedClassFor example, to create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject =
new OuterClass.StaticNestedClass();outer_x = 10 outer_private = 30 outer_y = 20
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.new InnerClass();There are two special kinds of inner classes :
outer_x = 10 outer_y = 20 outer_private = 30
| S.No. | Normal/Regular inner class | Static nested class |
|---|---|---|
| 1. | Without an outer class object existing, there cannot be an inner class object. That is, the inner class object is always associated with the outer class object. | Without an outer class object existing, there may be a static nested class object. That is, a static nested class object is not associated with the outer class object. |
| 2. | As the main() method can't be declared, the regular inner class can't be invoked directly from the command prompt. | As the main() method can be declared, the static nested class can be invoked directly from the command prompt. |
| 3. | Both static and non-static members of the outer class can be accessed directly. | Only a static member of an outer class can be accessed directly. |