The local classes (method local inner classes) are rarely used. It can be useful when any repeated functionality is required inside a method and if we are NOT interested to create class level method (may be because this functionality we may not require outside of method) for example, lets assume sum & mul methods are repeatedly require in our code (any particular method), one way to create a class level methods and call them whenever required, but what if these methods no longer required outside this method, in this case we may think of creating a local inner class and access its sum method whenever required only within that method, below example
class Outer {
public void calculations() {
class Inner {
public int sum(int x, int y) {
System.out.println("sum : " + (x+y));
return x+y;
}
public int mul(int x, int y) {
System.out.println("multiplication : " + (x*y));
return x*y;
}
}
Inner i= new Inner();
//some code...
i.sum(10, 20);
//some code...etc
i.mul(30, 40);
i.mul(14, 12);
i.sum(10000, 20000);
//some other code...
}
}
public class TestClass {
public static void main(String[] args) {
new Outer().calculations();
}
}