JAVA does not support “directly” nested methods, but you can still achieve nested method functionality in Java 7 or older version by defining local classes, class within method so that it will compile. In java 8 and newer version you achieve it by lambda expression.
Method 1 (Using anonymous subclasses)
It is an inner class without a name and for which only a single object is created. An anonymous inner class can be useful when making an instance of an object with certain “extras” such as overloading methods of a class or interface, without having to actually subclass a class.
// Java program implements method inside method
public class Hello {
interface myInterface { //create a local interface with one abstract method run()
void run();
}
// function have implements another function run()
static void Foo() //implement run method inside Foo() function.
{
myInterface r = new myInterface() {
public void run()
{System.out.println("Hello");};
};
r.run();
}
public static void main(String[] args) {
Foo();
}
}
Method 2 (Using local classes)
You can also implement a method inside a local class. A class created inside a method is called local inner class. If you want to invoke the methods of local inner class, you must instantiate this class inside method.
// Java program implements method inside method
public class Hello {
static void Foo() //function have implementation of another. Function inside local class
{
class Local { //local class
void fun()
{ System.out.println("Hello"); }
}
new Local().fun();
}
public static void main(String[] args) {
Foo(); }
}
Method 3 (Using a lambda expression)
Lambda expressions basically express instances of functional interfaces (An interface with single abstract method is called functional interface. An example is java.lang.Runnable).
lambda expressions implement the only abstract function and therefore implement functional interfaces.
// Java program implements method inside method
public class Hello {
interface myInterface {
void run();
}
static void Foo() //function have implements another function, run() using lambda expression
{
myInterface r = () -> //Lambda expression
{
System.out.println("Hello");
};
r.run();
}
public static void main(String[] args)
{
Foo();
}
}
Hope this helps!
Check out this Java Course to learn more.
Thanks!