Java - Constructors
Java - Constructors
B.Bhuvaneswaran
Assistant Professor (SS)
Department of Computer Science & Engineering
Rajalakshmi Engineering College
Thandalam
Chennai 602 105
bhuvaneswaran@rajalakshmi.edu.in
Constructors
It can be tedious to initialize all of the
variables in a class each time an instance
is created.
Java allows objects to initialize themselves
when they are created.
This automatic initialization is performed
through the use of a constructor.
Program
Output
Constructing Box
Constructing Box
Volume is 1000.0
Volume is 1000.0
In the line
Box mybox1 = new Box();
new Box( ) is calling the Box( ) constructor.
When you do not explicitly define a constructor for a class,
then Java creates a default constructor for the class.
This is why the preceding line of code worked in earlier
versions of Box that did not define a constructor.
The default constructor automatically initializes all instance
variables to zero.
The default constructor is often sufficient for simple classes,
but it usually wont do for more sophisticated ones.
Once you define your own constructor, the default
constructor is no longer used.
Parameterized Constructors
While the Box( ) constructor in the
preceding example does initialize a Box
object, it is not very usefulall boxes
have the same dimensions.
What is needed is a way to construct Box
objects of various dimensions.
The easy solution is to add parameters to
the constructor.
Program
Output
Volume is 3000.0
Volume is 162.0
Caution
Garbage Collection
References