1. Overloading of main method
1 package cn.nxl2018; 2 3 public class Main_test { 4 public static void main(String args[]) { 5 System.out.println("application entry main method" ); 6 main(); 7 main(10 ); 8 main(10, 10 ); 9 } 10 public static void main(){ 11 System.out.println("main method without parameters" ); 12 } 13 public static void main(int i){ 14 System.out.println("Overloaded main method with parameters" ); 15 } 16 public static void main( int i, int j){ 17 System.out.println("With two parameters Overload main method" ); 18 } 19 }
The above example shows that the main method can be overloaded, the parameters of each main method are different, the program can be run, and the expected results can be output. However, if there is no main method for program entry, there are only other main methods. Although compiling this program will pass, it will generate an error when run. This is because when the program is running, the Java virtual machine cannot find the corresponding main method, and an operation error will occur.
2. Invocation of the main method
1 public class Main_test { 2 public static void main(String[] args) { 3 main2(args); 4 } 5 public static void main2(String[] args){ 6 main(args); 7 } 8 }
After running the program, the program executes the two main methods infinitely recursively, and it is obvious that the main method can be called.
3. Inheritance of main method
Main.java:
1 public class Main{ 2 public static void main(String[] args) { 3 System.out.println("Hello Word!"); 4 } 5 }
Main_test.java:
1 public class Main_test extends Main{ 2 }
After compiling and running Main_test.java, "Hello Word!" is output, indicating that the main method can be inherited.
4. Hiding the main method
Main.java:
1 public class Main{ 2 public static void main(String[] args) { 3 System.out.println("Main"); 4 } 5 }
Main_test.java
1 public class Main_test extends Main{ 2 public static void main(String[] args) { 3 System.out.println("Main_test"); 4 } 5 }
Obviously the main method in the parent class Main is hidden, and the result shows the contents of the main method in the subclass.
Associated blog (blog garden):