方法里面的方法 [英] Methods inside methods
问题描述
在Java中使用main方法中的方法在语法上是否正确?例如
Is it syntactically correct to have a method inside the main method in Java? For example
class Blastoff {
public static void main(String[] args) {
//countdown method inside main
public static void countdown(int n) {
if (n == 0) {
System.out.println("Blastoff!");
} else {
System.out.println(n);
countdown(n - 1);
}
}
}
}
推荐答案
不,不是直接;但是,方法可能包含本地内部类,当然内部类可以包含方法。 这个StackOverflow问题给出了一些例子。
No, not directly; however, it is possible for a method to contain a local inner class, and of course that inner class can contain methods. This StackOverflow question gives some examples of that.
在你的但是,你可能只想从 main
里面调用倒计时
;你实际上并不需要它的整个定义在 main
里面。例如:
In your case, however, you probably just want to call countdown
from inside main
; you don't actually need its entire definition to be inside main
. For example:
class Blastoff {
public static void main(String[] args) {
countdown(Integer.parseInt(args[0]));
}
private static void countdown(int n) {
if (n == 0) {
System.out.println("Blastoff!");
} else {
System.out.println(n);
countdown(n - 1);
}
}
}
(请注意,我是声明倒计时
为 private
,因此只能在 Blastoff中调用 class,我假设你的意图是什么?)
(Note that I've declared countdown
as private
, so that it can only be called from within the Blastoff
class, which I'm assuming was your intent?)
这篇关于方法里面的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!