Why can other methods be “static” but a constructor cannot?

后端 未结 15 1241
借酒劲吻你
借酒劲吻你 2020-12-04 17:59

I do not understand why the main method has to be static. I understand static variables but static methods are difficult for me to grasp. Do static method exists so that one

15条回答
  •  被撕碎了的回忆
    2020-12-04 18:27

    Java has [static constructors] static initialization blocks which can be viewed as a "static constructor":

    class Foo {
      static String Bar;
      static {
         // "static constructor"
         Bar = "Hello world!";
      }
    }
    

    In any case, the only method in the main class which must be static is the main method. This is because it is invoked without first creating an instance of the "main class". A common technique, and the one I prefer, is to quickly get out of static context:

    class Main {
       int argCount;
    
       // constructor
       public Main (String[] args) {
         // and back to boring ol' non-static Java
         argCount = args.length;       
       }
    
       void runIt () {
          System.out.println("arg count: " + argCount);
       }
    
       // must be static -- no Main instance created yet
       public static void main (String[] args) {
          Main me = new Main(args);
          me.runIt();
       }
    }
    

    Also, static has nothing to do with "name clashes". A static method (or variable) is simply a method (or variable) that is not associated with a specific instance of a type. I would recommend reading through the Classes and Objects Java Tutorial and the section Understanding Instance and Class Variables.

    Happy coding.

提交回复
热议问题