开发者

Function within a function in Java [duplicate]

This question already has answers here: Nested functions in Java (8 answers) Closed 6 years ago.

Is it possible to define a function within a function in Java? I am trying to do so开发者_如何学Pythonmething like:

public static boolean fun1()
{
  static void fun2()
  {
     body of function.
  }
  fun();
  return returnValue;
}

but I am getting error Illegal start of expression.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜