Nested class examples

In this example we shall show you how to create a nested class. To create a nested class we have performed the following steps:

  • We have created class MN that has a method f() and an inner class A.
  • Class A has also a method g() and another class B.
  • Class has a method h() that calls g() method of A and f() method of MN.
  • Since B is a nested class it can access all members of all levels of the classes it is nested within.
  • We create a new instance of MN, and then using the MN object we create a new instance of A, and using A object we create a new instance of B and call its h() method,

as described in the code snippet below.

package com.javacodegeeks.snippets.core;

//Nested classes can access all members of all levels of the 
//classes they are nested within.

public class NestedClass {

    public static void main(String[] args) {

  MN mna = new MN();

  MN.A mnaa = A();

  MN.A.B mnaab = B();


class MN {

    private void f() {

  System.out.println("Function MN.f()");

    class A {

  private void g() {

System.out.println("Function A.f()");


  public class B {

void h() {






Function A.f()
Function MN.f()

This was an example of how to create a nested class in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button