You are on page 1of 7

Java Constructor

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.

Prepared by: Md. Saidur Rahman

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.

Default constructor is created only if


there are no constructors.
Prepared by: Md. Saidur Rahman

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.

Prepared by: Md. Saidur Rahman

Differences between
methods and constructors
(cont.)

Thefirst lineof a constructor must either


be a call on another constructor in the
same class (using this), or a call on the
super class constructor (usingsuper).

If the first line is neither of these, the


compiler automatically inserts a call to
the
parameterless
super
class
constructor.
Prepared by: Md. Saidur Rahman

Constructor
Syntax:
<access_modifier> ConstructorName
( [parameter_lists] )
{
// Initialization Statement(s);
}

Prepared by: Md. Saidur Rahman

Constructor: Example
Output:

Prepared by: Md. Saidur Rahman

You might also like