Function within a function in Java [duplicate]
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.
精彩评论