Function within a function in Java

The reason you cannot do this is that functions must be methods attached to a class. Unlike JavaScript and similar languages, functions are not a data type. There is a movement to make them into one to support closures in Java (hopefully in Java 8), but as of Java 6 and 7, it's not supported. If you wanted to do something similar, you could do this:

interface MyFun {
    void fun2();
}

public static boolean fun1()
{
  MyFun fun2 = new MyFun() {
      public void fun2() {
          //....
      }
  };
  fun2.fun2();
  return returnValue;
}

You cannot (and in Java they are called methods).

You can, however, define an anonymous class inside of a method, and call its methods.

Tags:

Java