Java Constructors
Class has instance variables,methods and constructors also.
A constructor in Java is a special method that is used to initialize objects.
The constructor is called when an object of a class is created.
when new keyword is used,constructed is invoked.
It can be used to set initial values for object attributes(variables)
Note that the constructor name must match the class name, and it cannot have a return type (like void).
Also note that the constructor is called when the object is created.
All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you. However, then you are not able to set initial values for object attributes.
Types of Constructors
Default Constructor
A constructor that is automatically provided by the compiler if you donβt write any constructor.
No need to write explicitly.
for instance variables,defaults values are given

Note:Local variables DO NOT get default values.
this keyword:
this is a reference variable that refers to the current object.
Why do we need this?
To differentiate between:
Instance variable
Method parameter
Parameterized Constructor:
A constructor that accepts arguments to initialize variables.
Top comments (0)