A constructors in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes. In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling the constructor, memory for the object is allocated in the memory. It is a special type of method that is used to initialize the object. Every time an object is created using the new() keyword, at least one constructor is called. There are certain properties of constructors in java.
Properties of Constructors
1. Constructor Should not have any return type
If we declare a return type for a constructor, JVM considers it a normal method. The basic aim of the constructor is to assign a value to the object. It implicitly returns the address of the object.
2. The access specifier of the constructor can be private, default, protected, public
If the access specifier of the constructor is private, then an object of the corresponding class can be created in the context of the same class but not in the context of another class. If the access specifier of the constructor is the default, then an object of the corresponding class can be created in the context of classes that are in the same package. Similarly, if the constructor is declared as protected, the object of the corresponding class can be created in the context of classes of the same package as well as inherited classes of other packages. And, if the constructor is declared as public, the object of the corresponding class can be created in the context of any class.
3. A constructor cannot be declared as final and synchronized
The main purpose of using the final keyword is to restrict the overriding of a method (basically overriding is done in the context of inherited classes). As there is no concept of overriding constructors, declaring the final is useless. Using synchronized for a constructor raises a syntax error. Because only the thread that creates an object should have access to it while it is being constructed.
Java
class GFG { final GFG() {} public static void main(String[] args) { System.out.println( "GFG!" ); } } |
Output:
./GFG.java:2: error: modifier final not allowed here final GFG() {} ^ 1 error
This snippet of code results in a compile-time error.
4. A constructor can invoke another constructor of the same class
By using this() as the first statement in a constructor we can call another constructor of the same class. If we want to invoke a parameterized constructor, we can pass a parameter list as an argument: this(parameter list). super() is used to invoke the constructor of the superclass. JVM implicitly declares the first statement as super() for the no-argument constructor, and this() for the default constructor.