The main features of the constructor

1. The name of the constructor must be exactly the same as the class name. In java, a normal function can have the same name as a constructor, but it must have a return value;
2. The function of the constructor is mainly used to define the initialized state when the object of the class is created. It has no return value and cannot be decorated with void. This ensures that not only does it automatically return nothing, but it doesn't have any options at all. And other methods have return value, even void return value. Although the method body itself does not automatically return anything, it is still possible to make it return something that may be unsafe;
3. The constructor cannot be called directly, it must be called automatically when the object is created through the new operator ; the general method is called when the program executes it;
4. When defining a class, the constructor of the class is usually displayed, and the work of specifying initialization in the function can also be omitted, but the Java compiler will provide a default constructor. This default constructor is not with parameters. The general method does not have this feature;
5. The constructor has the effect of rolling back. When the constructor throws an exception, it constructs an incomplete object, which will be rolled back and release the members of this incomplete object (c++)
6. When a class only defines a private constructor, its object cannot be created through the new keyword. When a class does not define any constructor, the C# compiler will automatically generate a default no-argument constructor for it.  [1] 
7. In Python, the constructor must be implemented by overriding the __init__ method

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325337360&siteId=291194637