Nested classes in java


Java allows to define a class inside another class, known as nested classes. There are four types of nested classes in java.

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

Static nested classes

In the example below : Car is an outer class and whereas Wheel is a static inner class. Both classes has the print method. To create the instance of Wheel you must reference it by prefixing it with the outer class name. Have a look at the main method.

Output of the program

Non-Static nested classes

Non-static nested classes are also called inner classes. They are associated with the instance of outer class therefore you need to create the instance of outer class to create the instance of inner class.

Shadowing

If an inner class declares fields or methods with the same names as field or methods in its outer class, the inner fields or methods are said to shadow over the outer fields or methods. Find out the example below:

Output of the program shadowing

Anonymous classes

A class defined without a class name are known as the anonymous class. Such classes can be defined as an experssion and instatiated on the fly. They are declared as either subclasses of an existing class or as implemenation of some interface. Here is an example that declares an anonymous subclass of a superclass called SuperClass:

Local classes

Local classes are like inner (non-static nested) classes that can be define in the context of a block as in a method body or a local block, just like as local variables can be defined in a method body and their scope is within the method body.

  • Local classes can only be accessed from inside the method or scope block in which they are defined
  • Local classes can access members (fields and methods) of its enclosing class just like regular inner classes
  • Local classes can also access local variables inside the same method or scope block, provided these variables are declared final
  • The same shadowing rules apply for local classes as for inner classes

No Responses