Key points:
⚫ Constructor can have all ‘4’ access modifiers (public, protected, private,
default).
⚫ If there is no constructor in a class, compiler automatically creates a default
constructor.
⚫ The access modifier for the default constructor provided by the compiler will
be SAME as the access modifier as class. (If the class is public then
constructor is also public OR If the class is default then constructor is also
default).
⚫ The default constructor given by the compiler will have only ‘2’ access
modifiers ie., public & default.
⚫ Compiler will provide a default constructor when there are no constructors in
the class.
⚫ We can code/write default constructor (or) parameterized constructor basing
upon our programming requirements.
⚫ If we declare a constructor as ‘private’ then we can restrict the object
creation of our class in other classes.
⚫ A Constructor is called simultaneously at the time of object creation by
using ‘new’ keyword.
⚫ In constructor we can write a ‘return’ statement without returning any value
(Just like void method).
⚫ We can create a class object by using “new” keyword and “available
constructor” .
⚫ CONSTRUCTOR OVERLOADING IS POSSIBLE OVERRIDDING IS
NOT POSSIBLE.
Constructor Vs Method
Constructor Method
Constructor is used to initialize Method is used to expose
the state of an object.
behaviour of an object.
Constructor must not have Method must have return type.
return type.
Constructor is invoked implicitly. Method is invoked explicitly.
The java compiler provides a Method is not provided by
default constructor if you compiler in any case.
don't have any constructor.
Constructor name must be same Method name may or may not
as the class name. be same as class name.