[JAVA] Inner class usage example

When do you use the inner class?

Use this when you want to clarify that an instance or method of a class is related. If there is a case where what is defined in the inner class is required by itself, it is better to define it at the top level instead of the inner class.

Usage example ①

** Use as a useful helper class when used with an external class. ** **

For example, let's define a calculator class that can perform four arithmetic operations. The following is an example of the calculator class defining the supported calculation operations in the inner class enum.

Inner class example


public class Calculator {
  public enum Operation {
    PLUS      { public int apply(int x, int y) { return x + y; } },
    MINUS     { public int apply(int x, int y) { return x - y; } },
    MULTIPLY  { public int apply(int x, int y) { return x * y; } },
    DIVIDE    { public int apply(int x, int y) { return x / y; } };
    public abstract int apply(int x, int y);
  }
  public int calc(Operation operation, int x, int y) {
    return operation.apply(x, y);
  }
}

Inner class example_Example of use


public class Main {
  public static void main(String[] args) {
    Calculator calculator = new Calculator();
    int result = calculator.calc(Calculator.Operation.PLUS, 2, 3);
    System.out.println(result);
    //=> 5
  }
}

Usage example ②

** If you want to define a class related to an outer class **

Where to use inner classes in Java standard library

■ Define Iterator related to java.util.ArrayList  2019-08-03 11.11.23.png ■ Define Iterator related to java.util.LinkedList  2019-08-03 11.12.11.png ■ HashIterator related to java.util.HashMap  2019-08-03 11.13.29.png

It seems that the inner class is used when you want to define related to the class such as Iterator of ArrayList and Iterator of HashMap.

Recommended Posts

Inner class usage example
Interface usage example
Java inner class review
Example of using abstract class
How to define an inner class bean