Skip to main content

What is Inner Class in Java with examples | Types of inner classes | Nested Class

Inner class and its 4 types with example

Inner class and its 4 types with example

When a class defined inside another class known as inner class.

public class OuterClass {

    class InnerClass {
        
    }
}

When to use Inner Classes?

Without existing one type of object, if there is no chance of existing another type of object then we should go for inner classes. example, University consists of several colleges, without existing University there is no chance of colleges hence we have to declare college class inside University class.

// Outer Class
public class University {

    // Inner Class
    class College {
       
    }
}

See another example.

Map is group of key value pair and each key value pair is called Entry. Without existing Map object there is no chance of Entry object, hence Interface Entry is defined inside Map Interface.

// Outer Interface
public interface Map<K, V> {

    // Inner Interface
    interface Entry<K, V> {
       
    }
}

Without existing outer class, there is no chance of existing inner class object.

Outer and inner class is Has-A Relationship. (Composition or Aggregation)

There are four types of inner classes in Java.

  1. Regular or Nested inner class
  2. Method Local inner class
  3. Anonymous inner class
  4. Static nested class

1. Regular or Nested inner class

If there is any named class directly inside another class, without static modifier such types of inner classes called Regular or Nested inner class.  

// Outer Class
public class OuterClass {

    // Inner Class
    class InnerClass {
       
    }
}

When we compile OuterClass.java it creates two class file named 

  • OuterClass.class
  • OuterClass$InnerClass.class

Inside inner class we can not declare any Static members. 

Note : In Regular inner classes, without an outer class object existing, there can not be any inner class object.

Learn how to call inner class methods:

How we can access inner class members? | How to access inner class code from static area of outer class?

  • First we have to create outer class object.
  • After create inner class object using outer object reference. lets see example for better understanding. 

Example 1 : Calling inner class method from outer class

class OuterClass {

    class InnerClass {
        public void innerClassMethod() {
            System.out.println("Inner class");
        }
    }
    
    public static void main(String[] args) {
        OuterClass obj1 = new OuterClass();
        OuterClass.InnerClass obj2 = obj1.new InnerClass();
        obj2.innerClassMethod();
    }
}

Output :

Inner class

We can also create inner class object in 1 line.

new OuterClass().new InnerClass().innerClassMethod();

2. Method Local inner class

When any class declared inside method, it is called as Method local inner class.

What is need of method local inner class?

The main purpose of method local inner class is to define method specific repeatedly required functionality.

Method local inner class are best suitable to meet nested method requirement.

We can access method local inner classes only within a method where we declared, outside of method we can not access. because of less scope method local inner class are rarely used.

Example 2 : Method local inner class 

public class MethodLocalInnerClass {

    public void outerMethod() {
       
        class Inner {
            public void multiply(int a, int b) {
                System.out.println("Multiplication is : "+ a*b);
            }
        }
       
        Inner obj = new Inner();

        // Call multiply method repeatedly
        obj.multiply(2, 2);
        obj.multiply(4, 4);
        obj.multiply(5, 2);
        obj.multiply(6, 3);
    }
    
    public static void main(String[] args) {
        MethodLocalInnerClass obj = new MethodLocalInnerClass();
        obj.outerMethod();
    }
}

Output :

Multiplication is : 4
Multiplication is : 16
Multiplication is : 10
Multiplication is : 18

We can declare method local inner class inside both instance and static method. 

  • If we declare inner class inside instance method then from method local inner class we can access both static and non static members of outer class directly.
  • If we declare inner class inside static method then we can access only static members of outer class directly from that method local inner class.

Lets see example.

Example 3 : Accessing static and non static members of outer class from instance method inside method local inner class 

public class MethodLocalInnerClass {

    int a = 10;
    static int b = 20;
    
    public void outerMethod() {
       
        class Inner {
            public void innerClassMethod() {
                System.out.println(a);
                System.out.println(b);
            }
        }
       
        Inner obj = new Inner();
        obj.innerClassMethod();
    }
    
    public static void main(String[] args) {
        MethodLocalInnerClass obj = new MethodLocalInnerClass();
        obj.outerMethod();
    }
}

Output :

10
20

So you can see we can directly access both static and non static members from instance method, but if we declare outerMethod() as static then we get following compile time error. because a variable is non static and outerMethod() is static.

Unresolved compilation problem:
    Cannot make a static reference to the non-static field a

From method local inner class, we can not access local variables of methods in which we declare inner class.

If local variable declare as final then we can access.

Points to remember :

  • We can not declare static method inside local method inner class. (As in above code we can not declare innerClassMethod() as static).

3. Anonymous inner class

When any inner class is declare without name, it is called as Anonymous inner class. 

In simple term, Anonymous inner class means name less inner class.

The main purpose of Anonymous inner class is just for instant use or one time use.  

Based on declaration and behavior there are 3 types of inner classes.

  1. Anonymous inner class that extends a class
  2. Anonymous inner class that implements interface
  3. Anonymous inner class that defined inside arguments

Learn more about Anonymous inner class in details :

4. Static nested class

When any inner class declared with static modifier, such types of inner classes are called static nested classes. 

In normal or regular inner class, without existing outer class object there is no chance of existing inner class object. So there is inner class is strongly associate with outer class object.

But in static nested class, without existing outer class object there may be chance of existing nested class object. hence, static nested class object is not strongly associated with outer class object. Lets see simple example for better understanding.

Example 4 : Static nested class example (access static class inside outer class)

class Outer {

    static class StaticNested {
       
        public void method() {
            System.out.println("Static nested class");
        }
    }
    
    public static void main(String[] args) {
       
        StaticNested obj = new StaticNested();
        obj.method();
       
    }
}

Output :

Static nested class

If we want to access static class outside of outer class then we have to write something like this :

Outer.StaticNested = new Outer.StaticNested();

In regular inner class, we can not declare static members but in static nested class we can declare static members including main method.

 

Happy Learning... Happy Coding...

Other articles :


Comments

Popular posts from this blog

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:  0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1]  There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.st

Flipping the Matrix HackerRank Solution in Java with Explanation

Java Solution for Flipping the Matrix | Find Highest Sum of Upper-Left Quadrant of Matrix Problem Description : Sean invented a game involving a 2n * 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n *n submatrix located in the upper-left quadrant of the matrix. Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal.  Input : matrix = [[1, 2], [3, 4]] Output : 4 Input : matrix = [[112, 42, 83, 119], [56, 125, 56, 49], [15, 78, 101, 43], [62, 98, 114, 108]] Output : 119 + 114 + 56 + 125 = 414 Full Problem Description : Flipping the Matrix Problem Description   Here we can find solution using following pattern, So simply we have to find Max of same number of box like (1,1,1,1). And last