Why can other methods be “static” but a constructo

2019-01-16 13:45发布

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 can create two methods with the same name in two different classes that won't clash with each other?

Also, I don't understand why I can't create a static constructor.

Could anyone help explain this concept?

12条回答
Ridiculous、
2楼-- · 2019-01-16 14:32

The main(String[]) method has a specific prototype that is dictated by how the Java runtime environment works. When you invoke java MyApplication from the command line, the Java VM will look for a static main(String[]) method contained in that class in order to execute the application. If that method is not found, then the Java VM can't run the class as an application. That's just how the language is defined. It also means that the Java VM doesn't create an instance of your application class in order to run it.

Now, if you want your class to be usable either as a standalone application or as an instance that's created by something else, then you can have your class implement the Runnable interface, and also provide a main method that executes the run method on a new instance.

public class MyRunnableThing implements Runnable
{
    // Define whatever variables your runnable thing needs here as
    // private instance fields.

    /** Fulfills requirements of Runnable interface. */
    public void run()
    {
        System.out.println( "I'm running..." ) ;
    }

    /** Also makes the class runnable from the console. */
    public static void main( String[] args )
    {
        MyRunnableThing runMeNow = new MyRunnableThing() ;
        runMeNow.run() ;
    }
}

Now any class could potentially create an instance of MyRunnableThing and use its run() method to produce the same behavior that would have been seen by executing java MyRunnablething.

See also: Working with Static Constructor in Java. Some highlights from that Q&A:

  • A constructor is used to create an instance of the class, so it's an instance method, not a static method.
  • You can create a static method that creates an instance of the class, using the constructor. This is how the trendy new "builder" classes work.
  • You can create a static method that returns a persistent, unique singleton instance.
  • If your class has static members, then you can create a static initializer to initialize the values of those members.
查看更多
Evening l夕情丶
3楼-- · 2019-01-16 14:32

Java does not permit to declare a constructor as static. Following are the reasons.

  1. Static means for the same class. i.e, static methods cannot be inherited.

  2. With static, "this" reference (keyword) cannot be used. "this" is always linked to an object. A constructor always belongs to some object.

  3. If a constructor is static, an object of subclass cannot access. If static is allowed with constructor, it is accessible within the class but not by subclass.

查看更多
混吃等死
4楼-- · 2019-01-16 14:42

The purpose of Constructor is to Construct an Object i.e. to initialize class's instance variables either their default values or by their initialized values. non-static Instance variables can't be accessed by static methods . So constructor is not static.

查看更多
时光不老,我们不散
5楼-- · 2019-01-16 14:44

A constructor cannot be static, because in an OO language, the process for creating an object is as follows:

  • allocate the object
  • call the constructor to initialise the newly-allocated object

Constructors are not used anywhere else (and a type-safe language should enforce this), so it follows that a constructor will always be called in a non-static context.

If a constructor were static, it would not receive a reference to the newly-allocated object, and thus would not be able to initialise it.

Thus, a constructor can always be non-static (as it is always called from a non-static context) and must always be non-static (otherwise it would be unable to perform its task).

查看更多
一夜七次
6楼-- · 2019-01-16 14:46

Constructor is used to create Objects.

Static is generally which is same for all objects.

So, if we have had static constructors creation of one object would affect all the other existing objects.

Static methods only reference to static variables. Therefore all the initial parameters which you are giving to create an object would change for all objects. It is no point creating similar objects for no use.

Hope this helps.... :)

查看更多
干净又极端
7楼-- · 2019-01-16 14:48

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.

查看更多
登录 后发表回答