The Secret of main
The reveal: your whole program was inside a class all along.
1public class Main {
2 public static void main(String[] args) {
3 System.out.println("My whole program is a class!");
4 }
5}
$ javac Main.java
$ java Main
My whole program is a class!
Every line, explained
public class Main {- Surprise: EVERY Java program lives inside a class! A real Java file is a class; this one is called Main, which is why the file is called Main.java and why we compile it with javac Main.java. (public means other code is allowed to see it.)
public static void main(String[] args) {- And here is our old friend. main is just a method inside the Main class! static means it belongs to the class itself rather than to one object, so Java can run it without building a new Main() first.
System.out.println("My whole program is a class!");- System.out.println(...) prints to the terminal, exactly as in Intro to Java.
}- This } closes the main method.
}- This } closes the Main class. Now you know what a complete, real Java file looks like, and you typed every line of it yourself. (One thing to know: a helper class like Dog sits beside Main in the file, not inside it.)