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

后端 未结 15 1161
借酒劲吻你
借酒劲吻你 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:19

    I am sharing one of the reason "why not a java constructor be static".

    Simply to say, "A java constructor is always non static" because,

    The purpose of the constructor is only to initialize/construct the object, and to make inheritance possible. To do these we need to use the two useful java keywords (cum non-static variables) such as this and super. We will use 'this' to initialize the object. We/Java will use super(ofcourse super()) to invoke super class constructor so that super object(or Object class) created first then the child object(hence the inheritance) If the constructor is static then we cant use that two keywords(non-static variables) inside the constructor(As we know non-static stuff cant be referenced from static context)

    So java constructors should not static.

    0 讨论(0)
  • 2020-12-04 18:22

    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.... :)

    0 讨论(0)
  • 2020-12-04 18:23

    On page 272 of Thinking In Java, 4th Edition, by Bruce Eckel, it says:

    ²The constructor is also a static method even though the static keyword is not explicit. So to be precise, a class is first loaded when any of its static members is accessed.

    A little bit more context.

    ... the compiled code for each class exists in its own separate file. That file isn't loaded until the code is needed. In general you can say "class code is loaded at the point of first use." This is usually when the first object of that class is constructed, but loading also occurs when a static field or static method is accessed.²

    This makes a lot of sense, if you think about the rule that says that a static method can't use non-static methods of the same class. I had this doubt a couple weeks ago when I couldn't understand how, using the Singleton Pattern, you could access the constructor inside the static method that is used to create a new instance of that class. Today I was flipping through the book and I came across this explanation.

    It also makes sense in a way that, if the constructor wasn't static, you'd first need an instance of that class to be able to access it, but I guess this could spark up the old discussion about the chicken or the egg.

    Hope it helped!

    0 讨论(0)
  • 2020-12-04 18:23

    Just take a look on this link, it will definately help you to understand: Why can't make a constructor static?

    AND

    Constructor is called at Run-time when we create Objects. Static is same for all objects but all objects have their own state and properties. So, if we have had static constructors creation of one object would affect all the other existing objects. Note: static is class level while constructors related to the objects.

    e.g.

      public class Foo
        {
           String name;
           int id;
            // define constructors
               Foo (String name, int id)
            {
                this.name = name;
                this.id = id;
            }
    
              p s v m(String[] arg)
          {
              Foo f1 = new Foo("Amit",001);
              Foo f2 = new Foo("Rahul",002);
          }
        }
    

    If we create static constructor then both objects(f1 also) will contain the last updated value regarding name and id as Rahul and 002.

    0 讨论(0)
  • 2020-12-04 18:23

    Constructors are neither entirely static (class level) or entirely non-static (instance level).

    • Unlike instance methods, constructors are not inherited.
    • Unlike static methods, a constructor can refer to this.

    So, why can't you declare a constructor static?

    Well, my take is that a (redundant) static keyword would be confusing and would not serve any purpose. Therefore they decided not to allow it.


    The explanation that static initialization blocks can be viewed as constructors is (IMO) conceptually wrong. (It is analogous to saying that an instance initialization block is a regular constructor. Which is equally wrong.)

    The key distinctions between static initialization and construction1 are:

    • static initialization happens at an indeterminate time2; there is no equivalent to new for class initialization,
    • there is no straight-forward way to pass (constructor) parameters to the initialization code
    • there is no practical way to recover from errors occurring during static initialization.

    1 - Hypothetically, if class initialization was explicit, then it would make sense to have static constructors. But the downsize would be that applications would need to explicitly "construct" all of the classes that they used ... which would be horrible.

    2 - You have a degree of control if you load a class dynamically, but even then if the class has already been loaded and initialized in the current classloader, then attempting to control initialization will fail.


    I do not understand why the main method has to be static.

    It has to be if you want the main method to act as an entrypoint for your application.

    The problem is that if main was an instance method, then there would need top be an instance of your entrypoint class to call the main method on. But how do you create it? Which constructor would you choose? What if there was no public constructor?

    The bottom line is that this is the way that Java was designed ... back in the 1990's ... and so far they have not seen the need to change this.


    0 讨论(0)
  • 2020-12-04 18:25

    Static methods belong to a class, not an object. The main method must be static because it is called first, before any other code has executed to instantiate any objects. It provides an entry point to the program. Static methods are called from outside of the container of an object. The same is true of static class variables. Only one copy exists for the entire class, as opposed to a member variable, which is created once for each object created from a class. They are used to store data for the class, such as the number of object instances have been created and not destroyed. This data belongs with the class. A good example of a static method is in the singleton pattern, where the constructor is private and can only be accessed by a static member function. A function outside the class would be unable to replicate this functionality. This method acts on class data and objects, so logically belongs to the same class. This all boils down to encapsulation. A class is responsible only for itself and knows only itself.

    On the other hand, object methods are meant to operate on the data associated with a single instance of a class, an object. Constructors are the code that is used to initialize an object and set it's data to an initial state. They are executed immediately (and automatically) after the memory has been allocated to store a new object. Even if you do not explicitly define a constructor, a kind of "default constructor" is executed in order to map the object's member variables and the object's method code to the new object.

    Hope this helps.

    0 讨论(0)
提交回复
热议问题