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

Constructor in JAVA

Author : ITVoyagers
Website : itvoyagers.in
Post :
https://itvoyagers.in/constr
uctor-in-java/
2 Content

 Why we need constructor?


Example
 Use of constructor.
 Type of constructor.
Example
 Rules for constructor.
 Advantages of constructor.

ITVoyagers - itvoyagers.in
3 Why we need constructor?
 Suppose we create a class Student with some attributes.

ITVoyagers - itvoyagers.in
4 Why we need constructor?
 So now if we want to create object of this class and assign values to its
variables we have to use instance of object.
 If we use instance of class object
to assign the value to variables
then it will increase the LOC.
 We have assign values to each
variable separately and this is
not possible with the classes
having more variables.
 This is where Constructor
comes in play.

ITVoyagers - itvoyagers.in
5 Use of constructor.

 Constructor help us to assign values to variables at the time of object creation.


 Constructor accept values as an attributes of object at the time of
creation.
 Every time we create object, default constructor has been called.
 Constructor can be use to display message.

Simple Definition
 Constructor is a method which name is same as class name and it get executed at
the time of object creation.

ITVoyagers - itvoyagers.in
6 Type of constructor.

 There are 2 types of constructor.


 Parameterized
 Non-Parameterized
 Parameterized
 Parameterized constructors are the one which helps up to accept values at the time of object
creation.
 Non-Parameterized
 Non-Parameterized don't accept values at the time of object creation, but they can be used to
display message.

ITVoyagers - itvoyagers.in
7 Parameterized Constructor

ITVoyagers - itvoyagers.in
8 Parameterized Constructor

 In above example when we pass values in Student class object


compiler called the constructor, which accepts values and assign
those values to global variables.
 Output :

ITVoyagers - itvoyagers.in
9 Non-Parameterized Constructor

ITVoyagers - itvoyagers.in
10 Non-Parameterized Constructor

 Non-Parameterized Constructor can be use to display the


message.
 Output :

ITVoyagers - itvoyagers.in
11 Rules for constructor.
 Constructor doesn't have any return type.
 Name of constructor is same as class’s name.

ITVoyagers - itvoyagers.in
12 Advantages of constructor.

We don’t have to use object instance for


assigning the values to class variables.
It helps to reduce LOC(Line of Code).

ITVoyagers - itvoyagers.in
Follow us on
13
https://www.facebook.com/itvoyagers/

https://twitter.com/ITVoyagers

https://www.instagram.com/itvoyagers_official/

https://www.reddit.com/user/ITVoyagers ITVoyagers

OFFICIAL https://in.pinterest.com/itvoyagers/

https://www.linkedin.com/in/itvoyagers-vgitcs-673642172/

https://www.slideshare.net/vgitcsofficialedupoi

ITVoyagers - itvoyagers.in

You might also like