7/13/2019
Java Constructor
Chapter-02
Mohammed Husain Bohara
Lecture map today
• Defining a Constructor in Java
• Constructor Overloading - Multiple Constructors for a Java Class
• Default, no-arg Constructor
• Constructor Parameters
• Calling a Constructor
• Calling a Constructor From a Constructor
• Calling Constructors in Superclasses cover in Inheritance
• Java Constructor Access Modifiers
1
7/13/2019
Example
class Test
{
// logic here
}
Create object of a Test class Test t = new Test();
NOTE: During the object creation constructor will be
executed
Instantiation vs. Initialization in context of
object
Instantiation //
Test t ;
Initialization //
t = new Test();
2
7/13/2019
How many different approach to create an
object in java?
What are the rules to declare constructor in
java?
3
7/13/2019
Few Question must have in ur mind about
constructor rules.
Why constructor name is same as class name?
Why return type is not allowed for constructor?
Can we declare constructor as public, private, protected?
Example
class Test /*
{ Test()
{
void m1() // empty implementation
{ }
S.O.P.(“M1 method”); */
}
P.S.V.M(String[] args){ Zero argument constructor
Test t = new Test();
} Type of default constructor
}
4
7/13/2019
Types of constructor
1. Default Constructor
(i) Always Zero argument constructor NOTE:
Default Constructor generated
by compiler and executed by
2. User define Constructor JVM
(i) Zero argument constructor
(ii) Parameterized constructor
User define constructor example (Constructor
Overloading )
class Test
{ void m1() { S.O.P.(“M1 method”); }
Test()
{ S.O.P.(“0-argument constructor”); }
Test(int a)
{ S.O.P.(“1-argument constructor”); }
P.S.V.M(String[] args){
Test t = new Test();
Test t1 = new Test(10);
t.m1(); t1.m1();
}
}
5
7/13/2019
Will it compile or not?
class Test
{
Default constructor will not be
Test(int a) Generated in this case
{ S.O.P.(“1-argument constructor”); } Compiler error
P.S.V.M(String[] args){
Test t = new Test();
Test t1 = new Test(10);
}
}
Design a program to calculate Rectangle area
and perimeter
1. Create two classes name as Rectangle and CalRectangle
1. Declare instance variable as length & width 1. Initialize object here (main
2. Create Rectangle constructor to initialize method)
instance variable 2. Set the length and width
3. Create setLength & setWidth method 3. Print area and perimeter
4. Create area and perimeter method and
return values to main method
6
7/13/2019
What is the purpose of constructor in
program?
Two purpose or two advantages of constructor
1. Constructor are user to write business logic of application those
logic are executed during object creation.
2. To understand second advantage, we must know use of this
keyword
7
7/13/2019
Case-01
class Emp{
int eid;
String ename;
float esal; Output:
void display(){ S.O.P.(“Emp id is : ”, +eid);
0
S.O.P.(“Emp name is : ”, +ename);
Null
S.O.P.(“Emp salary is : ”, +esal); } 0.0
P.S.V.M(String[] args){
Emp e = new Emp();
e.display();
}}
Case-02
class Emp{
int eid;
String ename;
float esal;
Output:
Emp() { eid=123; ename = “XYZ”, esal= 1000;}
123
void display(){ S.O.P.(“Emp id is : ”, +eid); XYZ
S.O.P.(“Emp name is : ”, +ename); 1000
S.O.P.(“Emp salary is : ”, +esal); }
P.S.V.M(String[] args){
Emp e = new Emp();
e.display();
}}
Constructor uses to initialize some values to instance variable during object creation
8
7/13/2019
What is the problem in case-02?
• With the given logic, for all the object of Emp class, same value will be
initialize
• Means different object but same value will initialize
What is the solution?
Parameterize constructor
Emp(int eid, String ename, float esal)
{
this.eid = eid;
this.ename = ename;
this.esal = esal;
}
Emp e1 = new Emp(111, “abc”, 1000);
Emp e2 = new Emp(222, “xyz”, 2000);
9
7/13/2019
How one constructor call to another
constructor?
Constructor calling
Example-1
class Test
{ Test()
{ this(10);
S.O.P.(“0-argument constructor”); }
Test(int a)
{ this(10,20);
S.O.P.(“1-argument constructor”); }
Test(int a, int b)
{ S.O.P.(“2-argument constructor”); }
P.S.V.M(String[] args){
Test t = new Test();
}}
10
7/13/2019
Will it compile or not?
class Test
{ Test()
{ S.O.P.(“0-argument constructor”);
this(10); }
Compiler
Test(int a)
error
{ S.O.P.(“1-argument constructor”);
this(10,20); } this()
Test(int a, int b) must be the
{ S.O.P.(“2-argument constructor”); } first
statement in
constructor
P.S.V.M(String[] args){
Test t = new Test();
}}
Will it compile or not?
class Test
{ Test()
{ Compiler error
this(10);
this(10,20); this()
S.O.P.(“0-argument constructor”); } must be the first
Test(int a) statement in
{ S.O.P.(“1-argument constructor”); } constructor
Test(int a, int b)
{ S.O.P.(“2-argument constructor”); }
P.S.V.M(String[] args){
Test t = new Test();
}}
11
7/13/2019
What is the conclusion from constructor
calling?
• One constructor is able to call only one constructor at a time because
one this statement is allowed
Can we create object inside constructor?
12
7/13/2019
Will it work or not?
class Test
It is possible to create object inside
{
constructor.
Test()
{
It will not give compile time error, but
new Test(); it is not recommended to create.
}
public static void main(String[] args) If we create object inside constructor,
{ it invokes the constructor recursively.
System.out.println("Main Method");
new Test(); Hence it cannot complete the process
} of Object creation.
}
Can we define a method with same name of class?
13
7/13/2019
Will it compile or not?
class Test
{
void Test()
{
System.out.println("This is a method not a constructor");
}
public static void main(String[] args)
{
System.out.println("Hello World!"); YES
Test t = new Test();
t.Test();
}
}
If we place return type in constructor prototype
will it leads to Error?
NO
Reason- No, because compiler and JVM considers it as a method.
14
7/13/2019
How compiler and JVM can differentiate
constructor and method definitions of both have
same class name?
Ans- A compiler and a JVM differentiates constructor and method
invocations by using 'new' keyword. If 'new' keyword is used in calling
then a constructor is executed else method is executed.
class Test Will it compile or not?
{
Test()
{
System.out.println("0-arg Constructor");
}
void Test()
{ Compile and
System.out.println("THis is method not
constructor"); run
} successfully
public static void main(String[] args)
{
By return type
System.out.println("Hello World!");
Test t = new Test();
t.Test();
}}
15
7/13/2019
How compiler and JVM can differentiate
constructor and method invocations of both have
same class name?
by new Keyword
What is the difference between constructor
and method in java?
write it in your own
16
7/13/2019
Java Constructor Access Modifiers
Constructors can have any of the access modifiers:
public, protected, private, or none.
Constructors cannot be abstract , final , native , static ,
or synchronized .
Copy Constructor
There are many ways to copy the values of one object into another in
java. They are:
• By constructor
• By assigning the values of one object into another
• By clone() method of Object class
17
7/13/2019
WHAT ?
A copy constructor is a constructor that takes only one argument which
is of the type as the class in which the copy constructor is
implemented.
For example, let us assume a class namely Car and it has a constructor
called copy constructor which expects only one argument of type Car.
WHY ?
• Copy constructors are widely used for creating a duplicates of objects
known as cloned objects.
• Duplicate object in the sense the object will have the same
characteristics of the original object from which duplicate object is
created.
• But we have to ensure that both original and duplicate objects refer
to different memory locations.
18
7/13/2019
Example
class CopyConstructor{
int id;
String name; public static void main(String args[]){
CopyConstructor(int i,String n){
id = i; CopyConstructor s1 = new
name = n; CopyConstructor(111,"Karan");
}
CopyConstructor s2 = new CopyConstructor(s1);
CopyConstructor(CopyConstructor s){
id = s.id;
name =s.name;
s1.display();
}
void display() s2.display();
{
System.out.println(id+" "+name); }
} }
Copying values without constructor
We can copy the values of one object into another by assigning the
objects values to another object.
19
7/13/2019
Example
class CopyConstructor{
int id; public static void main(String args[]){
String name; CopyConstructor s1 = new
CopyConstructor(int i,String n){ CopyConstructor(111,"Karan");
id = i; CopyConstructor s2 = new CopyConstructor();
name = n;
s2.id=s1.id;
}
s2.name=s1.name;
CopyConstructor(){}
s1.display();
void display()
s2.display();
{ }
System.out.println(id+" "+name); }
}
Concept of destructor in JAVA
What is the aim of destructor in any OOPs
language?
1. Free up the memory (c++ suffer from memory allocation / deallocation)
2. Clean up any other resources (like closing of open file stream)
20
7/13/2019
Java take cares of all and hence there is no
destructor in Java.
With the help of Garbage collection
finalize() method
class Thing {
public int number_of_things = 0;
public String what;
public class TestDestructor {
public Thing (String what) { public static void main(String[] args)
this.what = what;
number_of_things++; {
Thing obj = new Thing("Test App");
}
}
public void finalize () { }
number_of_things--;
}
}
21
7/13/2019
Any Question?
What is the output?
A. It print 0
B. It print Garbage Value
C. Compile time error
D. Run time error
22
7/13/2019
What is the output?
A. Student no is.. 1 student name is.. Satish
B. Compile time error in constructor
C. Run time error in constructor
D. Student no is.. 0 student name is.. null
Ans- D
What is the output?
A. compile time error
B. Run time error
C. It prints area is.. 12 and area is.. 25
D. It prints area is.. 25 and area is.. 25
Ans- D
23
7/13/2019
What is the output?
A. compile time error
B. Run time error
C. It prints area is.. 0 and area is.. 25
D. It prints area is.. 12 and area is.. 0
Ans- B
What is constructor overriding?
A. Constructors can not be overridden in Java
B. Since constructor are special function which can’t be inherited to
derived classes, so it is not possible for derived classes to override a
constructor of base class
C. Derived classes can call base class constructor by using super
keyword
D. All are correct
Ans- D
24
7/13/2019
Reference
https://deepeshdarshan.wordpress.com/2013/12/05/copy-
constructors-in-java/
25