Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 13

Constructors in Java

What is Constrctor?
A constructor in Java is a special
method that is used to initialize objects.
The constructor is called when an object of a
class is created. 
It is a special type of method which is used to
initialize the object.
Every time an object is created using the
new() keyword, at least one constructor is
called.
Need of Constructor
Think of a Box class & its object
When it comes to exist?
Can a box be there with no value defined for its
dimensions?
So constructors are used to assign values to the
class variables at the time of object creation, either
explicitly done by the programmer or by Java itself
(default constructor).
Rules for creating Java
constructor

There are two rules defined for the


constructor.
Constructor name must be the same as its
class name
A Constructor must have no explicit return
type
A Java constructor cannot be abstract,
static, final, and synchronized
Types of Java constructors
Java Default Constructor
A constructor is called "Default Constructor" when it doesn't
have any parameter.
Using this constructors the instance variables of a method will
be initialized with fixed values for all objects.
It is used to provide the default values to the object like 0,
null, etc., depending on the type.

Syntax of default constructor:


<class_name>()
{

}  
Default Constructor Example1

Output:-5
Default Constructor Example 2

Output:-
Java Parameterized Constructor
A constructor which has a specific number of parameters
is called a parameterized constructor.
It is used to provide different values to distinct
objects.You can provide the same values also
Java Parameterized Constructor Example

Output
Difference between Java Constructor &
Method
Java Copy Constructor
There is no copy constructor in Java.
We can copy the values from one object to another like copy
constructor in C++.
Ways to copy the values of one object into another
I. By constructor
II. By assigning the values of one object into another
III. By clone() method of Object class
Copy Constructor
A copy constructor is a special type of constructor that creates
an object using another object of the same Java class. It
returns a duplicate copy of an existing object of the class.
Copy Constrctor Example

Output

You might also like