Java Inner Classes With Examples

Java Inner Classes With Examples


Java Nested and Inner Class

In this tutorial, you will learn about the nested class in Java and its types with the help of examples.

In Java, you can define a class within another class. Such class is known as nested class. For example,

class OuterClass {
    // ...
    class NestedClass {
        // ...
    }
}

There are two types of nested classes you can create in Java.

  • Non-static nested class (inner class)
  • Static nested class

Recommended reading:

Let's first look at non-static nested classes.


Non-Static Nested Class (Inner Class)

A non-static nested class is a class within another class. It has access to members of the enclosing class (outer class). It is commonly known as inner class.

Since the inner class exists within the outer class, you must instantiate the outer class first, in order to instantiate the inner class.

Here's an example of how you can declare inner classes in Java.