Introduction To Nested Class In Java

Introduction

In this article, we discuss nested classes (inner classes) in Java.

Nested class

One of the nice and highly advantageous features of Java is the ability to define nested classes, in other words, classes within classes. In Java classes are either top-level-classes (a class defined directly within a package) or nested classes (classes defined within top-level-classes).

Syntax:

class MainClass

{

//some coding here

class NestedClass

{

//some coding here

}

}

Advantages

The main advantages of a nested (inner) class are:

It shows a special type of relationship, in other words, it has the ability to access all the data members (data members and methods) of the main class including private.

They provide easier code because it logically groups classes in only one place.

Reduces coding since we need less code to write.

Types

This can be divided into two categories:

static class

non-static class is also called as inner classes.

Static Classes

This class can't refer directly to their instance variables or methods defined in its enclosing class since they use them only by an object reference. They are accessed by the use of class name: