It's the same as any other code that gets executed - it has to be inside a method! (Yes, ish, for the purists, I'm also including constructors and static / instance initialiser blocks.) Think about it - if it wasn't inside a method or other related code block as you propose, then when would that code get executed? It wouldn't make much sense. You can't execute a class per-se, you can only execute a specific method / constructor / etc. contained within that class.
The only things allowed outside method and constructor declarations are declarations of fields. Since System.out.println()
is not a field declaration, it's not allowed.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…