Java Nested Classes | 4 Inner Types | Real Time Examples

Java Nested Classes | 4 Inner Types | Real Time Examples

In earlier tutorials we have seen, writing Java classes and creating objects. In this tutorial you will learn to write the nested classes, different types explained with real-time coding examples.

Let’s start.

What is Java Nested Classes?

In Java, we can create a class inside a class and this concept is referred to as nested classes.  The class within which a new class is written is called the outer class and the one written within is called nested class.

Syntax:

The basic syntax
of writing a nested class is given below:

class OuterClass {
     //code
     class InnerClass {
         //code
         }
 }

Use of Java Nested Classes:

The use of nested classes in the code is to optimizes the code and to develop code which is more easily maintainable and readable.

Types of Nested Classes in Java

There are by and large two types of nested classes
namely

  • Non-static nested classes
  • Static nested classes

The non-static nested classes are also referred as
the inner class. And these inner classes are further sub-divided into 3 variant
types, they are:

  • Anonymous Inner Class
  • Member Inner Classes
  • Local Inner Class

Now, let us in detail study all of the above-listed types.

1. Anonymous Inner Class

An inner class devoid of any name is known as an anonymous inner class. Such classes are easily reached only at the point where they are defined. Anonymous inner classes are declared and instantiated at the same point.

The general purpose of creating an anonymous inner class is
that if one has to override a method of class or interface. These classes can
be implemented using –

  • Class (which can be either abstract or concrete)
  • Interface

Let us have a sneak peek on how the anonymous inner class is implemented using both ways.

Example using the class:

abstract class Radio {
    abstract void playMusic( );
}
class AnonymousDemo {
    public static void main(String args[ ]) {
        Radio r = new Radio( ) {
            void playMusic( ) {
                System.out.println("Plays music!");
            }
        };
        r.playMusic( );
    }
}

Output:

Plays music! 

Example using interface:

interface Fruit {
    void juice();
}

class TestAnonymous
{
    public static void main(String args[ ])
    {
        Fruit f = new Fruit( ){
            public void juice() {
                System.out.println("Yummy Fruit Juice!");
            };
            f.juice();
        }
    }
}

Output:

Yummy Fruit Juice!

2. Member Inner Class

A kind of non-static class that is created inside another class however outside a method is defined as member inner class. The object of the member inner class in java is an element of the outer class object and to generate an instance of the inner class, we have to first create the instance of the outer class.

This kind of inner class also allows the user to access the private elements of the outer class. To better understand, member inner class, check out the below example.

Example:

class Outer
{
    private String data = "My program defines member inner class";
    class Inner
    {
        void print()
        {
            System.out.println(data);
        }
    }

    public static void main(String args [] )
    {
        Outer o = new Outer();
        Outer.Inner i = o.new  Inner();
        i.print();
    }
}

Output:

My program defines member inner class

3. Local Inner Class

An inner class that is created inside a method is called as a local inner class. Just like the local variables, the scope of the local inner class is constrained to within the method it is defined. This type of inner class can be instantiated only inside the method it is defined. It has access to all types of variables. To understand its real-time usage, see the below example:

Example:

class ExampleLocal
{
    private String data = "This is an instance variable.";

    void printData() {
        int number = 25;

        class LocalDemo {
          void displayMsg() {
            System.out.println(data);
            System.out.println("This is a local variable:" +number);
          }
        }

        LocalDemo obj = new LocalDemo();
        obj.displayMsg();

        public static void main(String args []) {
            ExampleLocal e = new ExampleLocal();
            e.printData();
        }
}

Output:

This is an instance variable.
This is a local variable: 25

Hitherto, we have seen in detail non-static nested classes, now
let us discuss static nested classes.

4. Static Nested Class

If the nested class is declared static, then it’s referred as static nested class. These types of classes have access to only static members of the outer class. It does not have access to non-static members or variables of the outer class.

Example:

class StaticDemo {
    static String data = "Static Inner Class";
	
    static class Inner {
    void print() {
        System.out.println(data);
    }

    public static void main(String args []) {
        StaticDemo.Inner obj = new StaticDemo.Inner();
        obj.print();
    }
}

Output:

Static Inner Class

We have seen what are nested classes, its varied types in detail. Let us examine what are nested interfaces now.

Before going further, I hope you have gone through our earlier tutorial- Java Interface explained with examples.

What are Nested Interfaces in Java?

 An interface that is declared and defined inside another interface is known as nested interfaces. The nested interfaces are declared statically implicit.  A nested interface can be declared either inside the class or inside an interface. The general syntax is as follows:

  • Inside a class
class <class_name> {
     interface <interface_name> {
         //code
     }
 }
  • Inside an interface
interface <interface_name> {
     interface <inner_interface_name> {
         //code
     }
 }

Simple examples of both cases are discussed below.

Case 1: nested interface inside a class

class Example {
  interface Data {
    void print();
  }
}

class Demo implements Example.Data {
  public void print() {
    System.out.println("Example: nested interface within a class.");
  }

  public static void main(String args[ ])
  {
    Example.Data d = new Example.Data();
    d.print();
  }
}

Output:

Example: nested interface within a class.

Case 2: nested interface inside an interface

interface Fruit {
  void display();

  interface juice {
    void print();
  }
}

class CheckDemo implements Fruit.juice {
  public void print() {
    System.out.println("Yummy Fruit Juice!");
  }

  public static void main(String args[]) {
    Fruit.juice obj = new Fruit.juice();
    obj.print();
  }
}

Output:

Yummy Fruit Juice!

That’s all about Java nested classes and nested interfaces. Try solving some real-time examples for understanding the concept of inner classes better. If you have any questions, feel free to ask me by commenting below.

Happy Learning!

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *