Constructor and Its Types
October 15th 2020 123
Constructors are used for initializing the object’s state. Like methods, a constructor also contains a collection of statements(i.e. instructions) that are executed at the time of Object creation. Every time an object is created using the new() keyword, at least one constructor is called to assign initial values to the data members of the same class. It is called constructor because it constructs the values at the time of object creation. It is not necessary to write a constructor for a class. It is because the java compiler creates a default constructor if your class doesn't have any.
Rules for writing constructor:
Types of constructor:
- No-argument constructor:
- Parameterized Constructor:
- If any assignment is not made to any class variable in both the constructor, default values are provided to class variables of the object like 0, null, etc depending on the data type.
- There are no “return value” statements in constructor, but constructor returns current class instance. We can write ‘return’ inside a constructor. Constructor(s) do not return any type while method(s) have the return type or void if does not return any value.
- Constructor Overloading is possible.