内部方法的方法

在Java中的main方法中有一个方法在语法上是否正确? 例如

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问题给出了一些例子。

但是,在你的情况下,你可能只想从main内部调用countdown ; 你实际上并不需要将它的整个定义放在main 。 例如:

 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); } } } 

(注意我已经将countdown声明为private ,因此只能在Blastoff类中调用它,我假设这是你的意图?)