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.
** 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
}
}
** If you want to define a class related to an outer class **
■ Define Iterator related to java.util.ArrayList ■ Define Iterator related to java.util.LinkedList ■ HashIterator related to java.util.HashMap
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.