In the java language, the constructor is also called the construction method.
The function of the constructor is to initialize the object, that is, it is called by the system when the object is created (unlike ordinary methods, the program cannot explicitly call the constructor). The constructor can also be overloaded, that is, parameters can be passed in. When the program contains a constructor with parameters, the system will no longer provide a parameterless constructor.
#When creating a class object, call its corresponding constructor method to create it. It is tedious to initialize all variables of a class every time it is created. (Recommended learning: Java Video Tutorial)
If an object completes all the initial work when it is created, it will be simple and concise. Therefore, Java provides a special member function in the class called the constructor. This is because the return value type of a class's constructor is the class itself. The task of the constructor is to initialize the internal state of an object, so after using the new operator to create an instance, you will immediately get a clear and usable object.
The construction method is a special method with the following characteristics.
(1) The method name of the constructor must be the same as the class name.
(2) The constructor method has no return type and cannot be defined as void. The method type is not declared in front of the method name.
(3) The main function of the constructor is to complete the initialization of the object. It can pass the parameters when defining the object to the object's domain.
(4) The construction method cannot be called by programmers, but must be called by the system.
(5) A class can define multiple constructors. If no constructor is defined when defining a class, the compilation system will automatically insert a parameterless default constructor, which does not execute any code.
(6) The construction method can be overloaded and distinguished by the number, type, or arrangement order of parameters.
For more Java-related technical articles, please visit the Java Development Tutorial column to learn!
The above is the detailed content of When is the constructor called?. For more information, please follow other related articles on the PHP Chinese website!