方法声明中修饰符和返回类型的顺序
当我将方法声明为 aspublic void static subMethod()而不是 时,为什么会出现编译时错误public static void subMethod()?
class Example{
public void static subMethod() {
System.out.println("A");
}
public static void main(String args[]) {
subMethod();
}
}
回答
因为规范是这么说的。
具体来说,顺序是:
modifiers returntype methodname(ArgType1 argName1, ArgType2 argName2, ...) { ... }
modifiers可以按您想要的任何顺序放置在哪里。例如static public void subMethod() {},同样合法,但请注意,就像在英语中一样,说“A green little book”听起来很奇怪,而正确地说“A little green book”public static听起来是对的,但static public听起来是错的。
void代替返回类型,因此不能成为修饰符的一部分,它大部分在它们之后(或者更确切地说,修饰符不能在 之后void)。
不要写String args[]。合法,但是,根本不习惯。改写String[] args。