Nested Classes in Java

There are 2 main types of nested class.

  1. Static nested class
  2. Non-Static nested class (Also called as Inner class)

Non-static (Inner class) classes can be divided into 3 types as mentioned below.

  1. Normal
  2. Method local
  3. Anonymous

Nested Class in Java

Below example will illustrate how to work with Nested classes.

package corejava.nestedclasses;

//Class A is an outer class
public class A {
    private int number;
    public String name;
    static private String city;

    //class B is an inner class (Non-Static)
    class B {
        public void printB(){
            System.out.println("This is non-static nested class " +
                    "so it can access private members of outer class" + name);
        }
    }

    public void hi() {
        //Class C is a method local inner class
        class C {
        }
        C c1 = new C();
    }

    //Static class
    static class D{
        public void print(){
            System.out.println("This is static inner class");
            System.out.println("I can not access non static " +
                    "members of outer but can access static memebrs" +
                    "like city in this case");

            //We can not access class C from here
            // as it is local to method hi() of outer class only
            //C c1 = new C();
        }
    }

    public static void main(String[] args) {
        D d1 = new D();
        d1.print();
    }
}

You may also like...