Java Constructor: 1 Prepared By: Md. Saidur Rahman
Java Constructor: 1 Prepared By: Md. Saidur Rahman
Constructors
When you create a new instance (a new
object) of a class using thenewkeyword,
aconstructorfor that class is called.
Constructors are used to initialize the
instance variables (fields) of an object.
Constructors are similar to methods, but
with some important differences.
Constructors (cont.)
A constructors must have thesame
name as the class its in and a
constructor has no return type.
Default constructor:
If you don't define a constructor for a class,
adefault parameterless constructoris
automatically created by the compiler.
Differences between
methods and constructors
There isno return typegiven in a
constructor signature (header). The
value is this object itself so there is
no need to indicate a return value.
There isno return statementin the
body of the constructor.
Differences between
methods and constructors
(cont.)
Constructor
Syntax:
<access_modifier> ConstructorName
( [parameter_lists] )
{
// Initialization Statement(s);
}
Constructor: Example
Output: