Constructor in Java
A constructor is a special method that has no return type and has the same name as the class in which it is used. The constructor is called when a new class object is created and determines the actions required to initialize it.
Default constructor
If a constructor is not defined for a class, the compiler will generate a constructor with no arguments - the so-called "default constructor".
public class ClassName() {}
If the class already has a defined constructor, then the default constructor will not be created and, if necessary, it must be described explicitly.
Difference between a default constructor, a copy constructor, and a constructor with parameters
The default constructor has no arguments. The copy constructor accepts an already existing class object as an argument for the subsequent creation of its clone. A constructor with parameters has in its signature arguments (usually required to initialize class fields).
Private constructor
A private (marked with the private keyword, hidden) constructor can be used by a public static method for generating objects of this class. Also, access to it is allowed by nested classes and can be used for their needs.
Read also:
- Object class in Java
- Autoboxing in Java and rules for wrapping primitive types in wrapper classes
- Class String in Java
Comments
Post a Comment