0% found this document useful (0 votes)
21 views

Java Constructor: 1 Prepared By: Md. Saidur Rahman

Constructors are special methods that initialize objects. They are called when new objects are created using the new keyword. Constructors have the same name as the class and do not have a return type. They initialize the object's fields and can call other constructors or the parent constructor. Constructors differ from regular methods in that they do not have a return type and cannot return values.

Uploaded by

Shafiqul Islam
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Java Constructor: 1 Prepared By: Md. Saidur Rahman

Constructors are special methods that initialize objects. They are called when new objects are created using the new keyword. Constructors have the same name as the class and do not have a return type. They initialize the object's fields and can call other constructors or the parent constructor. Constructors differ from regular methods in that they do not have a return type and cannot return values.

Uploaded by

Shafiqul Islam
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 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