SlideShare a Scribd company logo
1 of 16
Department of Computer Science, COMSATS University Islamabad - Wah Campus - Pakistan
Constructor overloading,
constructor chaining, and copy
constructor
(Java)
Contents
 Recap of previous lecture
 Function overloading
 Constructor overloading
 Constructor chaining
 Copy constructor
 References
 Next lecture
2
Recap of previous lecture/week
3
• Default – No keyword required
• Public
• Private
• Protected
• Default constructor
• No-argument constructor
• Parametrized constructor
Function overloading
4
First understand or revise the concept of function overloading
• Method Overloading is a
feature that allows a class to
have more than one method
having the same name, if
their argument lists are
different.
• It is similar to constructor
overloading in Java, that
allows a class to have more
than one constructor having
different argument lists.
Constructor overloading
5
• Constructor can be overloaded
• An overloaded constructor provides multiple ways to set up a new object
• Complier differentiates which constructor is to be called depending on the
signature (type, sequence, number of arguments).
• When we construct an object, the complier decides which constructor to invoke
according to the type of the actual parameter.
Constructor overloading syntax
6
Constructor overloading example
7
Constructor chaining
8
• Constructor Chaining is the process of calling one constructor of a class from
another constructor of the same class or another class using the current object of
the class.
• There are two ways by which we can use constructor chaining in Java. These ways
depend on whether we are using it in the same class or the different class.
Using this keyword
Using the super keyword (will discuss later)
Constructor chaining example
9
package ThisExample;
class Example
{
//non-parametrized constructor
Example()
{
System.out.println("Inside non-parametrized ");
}
//Parameterized constructor
Example(double x)
{
//calling non-parametrized constructor
this();
System.out.println("Inside Parameterized“+x);
}
package ThisExample;
public class ThisExample
{
public static void main(String arg[])
{
//calling the parameterized constructor
Example obj = new Example(15);
}
}
//Parameterized constructor
Example(int n)
{
//calling parametrized constructor
this(4.5);
System.out.println("Inside Parameterized“+n);
}
}
Copy constructor
10
• A Copy Constructor in Java is a special type of constructor that is used to create a
new object using the existing object of a class that we have created previously.
• It creates a new object by initializing the object with the instance of the same
class.
• The Java Copy Constructor provides a copy of the specified object by taking the
argument as the existing object of the same class.
• Java does not implicitly provide the facility of a Copy constructor as in C language.
• But, we can define it by copying the values of one object to another object.
Creating a Copy Constructor in Java
11
• To create a copy constructor in java, we need to first declare a constructor that
takes an object of the same type as a parameter. For example:
public class Student
{
private int roll ;
private String name;
// Declaring a copy constructor by passing the parameter as the class
public Student( Student student )
{ }
}
Creating a Copy Constructor in Java
12
• After declaring a copy constructor, we need to copy each field of the input object
of the class into the new object. For example:
public class Student
{
private int roll;
private String name;
// Copying each field of the existing object into the newly created object
public Student( Student student )
{
this.id = student.roll;
this.name = student.name;
}
}
Copy Constructor example
13
package Xyz;
public class Student
{
private int roll;
private String name;
//constructor to initialize roll number and name of the student
Student(int rollNo, String sName)
{
roll = rollNo;
name = sName;
}
//copy constructor
Student(Student student)
{
System.out.println("n---Copy Constructor Invoked---");
roll = student.roll;
name = student.name;
}
//method to return roll number
int printRoll()
{
return roll;
}
//Method to return name of the student
String printName()
{
return name;
}
}
Copy Constructor example
14
//class to create student object and print roll number and name of the student
package Xyz;
public class Xyz
{
public static void main(String[] args)
{
Student student1 = new Student(101, “ali");
System.out.println("Roll number of the first student: "+ student1.printRoll());
System.out.println("Name of the first student: "+ student1.printName());
//passing the parameter to the copy constructor
Student student2 = new Student(student1);
System.out.println("nRoll number of the second student: "+ student2.printRoll());
System.out.println("Name of the second student: "+ student2.printName());
}
}
Roll number of the first student: 101
Name of the first student: Ali
—Copy Constructor Invoked—
Roll number of the second student: 101
Name of the second student: Ali
References
15
• https://beginnersbook.com/2013/05/constructor-overloading/
• https://www.codesdope.com/java-constructor-overloading/
• https://www.guru99.com/java-constructors.html
• https://www.scientecheasy.com/2020/06/java-constructor-
overloading.html/
• https://beginnersbook.com/2013/05/method-overloading/
• https://techvidvan.com/tutorials/java-constructor-chaining/
16
THANK YOU

More Related Content

Similar to Java Constructor

Similar to Java Constructor (20)

ClassJS
ClassJSClassJS
ClassJS
 
Core java day4
Core java day4Core java day4
Core java day4
 
BCA Class and Object (3).pptx
BCA Class and Object (3).pptxBCA Class and Object (3).pptx
BCA Class and Object (3).pptx
 
Unit ii
Unit   iiUnit   ii
Unit ii
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
 
Constructor and desturctor
Constructor and desturctorConstructor and desturctor
Constructor and desturctor
 
oop 3.pptx
oop 3.pptxoop 3.pptx
oop 3.pptx
 
Constructor & Destructor
Constructor & DestructorConstructor & Destructor
Constructor & Destructor
 
Constructors in JAva.pptx
Constructors in JAva.pptxConstructors in JAva.pptx
Constructors in JAva.pptx
 
Constructor and destructor in oop
Constructor and destructor in oop Constructor and destructor in oop
Constructor and destructor in oop
 
Constructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfConstructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdf
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructor
 
21CSC101T best ppt ever OODP UNIT-2.pptx
21CSC101T best ppt ever OODP UNIT-2.pptx21CSC101T best ppt ever OODP UNIT-2.pptx
21CSC101T best ppt ever OODP UNIT-2.pptx
 
Constructors and destructors in C++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
Sonu wiziq
Sonu wiziqSonu wiziq
Sonu wiziq
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Constructors in java
Constructors in javaConstructors in java
Constructors in java
 
Chapter 7 - Constructors.pdf
Chapter 7 - Constructors.pdfChapter 7 - Constructors.pdf
Chapter 7 - Constructors.pdf
 
Chapter 7 - Constructors.pptx
Chapter 7 - Constructors.pptxChapter 7 - Constructors.pptx
Chapter 7 - Constructors.pptx
 

Recently uploaded

A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 

Recently uploaded (20)

A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 

Java Constructor

  • 1. Department of Computer Science, COMSATS University Islamabad - Wah Campus - Pakistan Constructor overloading, constructor chaining, and copy constructor (Java)
  • 2. Contents  Recap of previous lecture  Function overloading  Constructor overloading  Constructor chaining  Copy constructor  References  Next lecture 2
  • 3. Recap of previous lecture/week 3 • Default – No keyword required • Public • Private • Protected • Default constructor • No-argument constructor • Parametrized constructor
  • 4. Function overloading 4 First understand or revise the concept of function overloading • Method Overloading is a feature that allows a class to have more than one method having the same name, if their argument lists are different. • It is similar to constructor overloading in Java, that allows a class to have more than one constructor having different argument lists.
  • 5. Constructor overloading 5 • Constructor can be overloaded • An overloaded constructor provides multiple ways to set up a new object • Complier differentiates which constructor is to be called depending on the signature (type, sequence, number of arguments). • When we construct an object, the complier decides which constructor to invoke according to the type of the actual parameter.
  • 8. Constructor chaining 8 • Constructor Chaining is the process of calling one constructor of a class from another constructor of the same class or another class using the current object of the class. • There are two ways by which we can use constructor chaining in Java. These ways depend on whether we are using it in the same class or the different class. Using this keyword Using the super keyword (will discuss later)
  • 9. Constructor chaining example 9 package ThisExample; class Example { //non-parametrized constructor Example() { System.out.println("Inside non-parametrized "); } //Parameterized constructor Example(double x) { //calling non-parametrized constructor this(); System.out.println("Inside Parameterized“+x); } package ThisExample; public class ThisExample { public static void main(String arg[]) { //calling the parameterized constructor Example obj = new Example(15); } } //Parameterized constructor Example(int n) { //calling parametrized constructor this(4.5); System.out.println("Inside Parameterized“+n); } }
  • 10. Copy constructor 10 • A Copy Constructor in Java is a special type of constructor that is used to create a new object using the existing object of a class that we have created previously. • It creates a new object by initializing the object with the instance of the same class. • The Java Copy Constructor provides a copy of the specified object by taking the argument as the existing object of the same class. • Java does not implicitly provide the facility of a Copy constructor as in C language. • But, we can define it by copying the values of one object to another object.
  • 11. Creating a Copy Constructor in Java 11 • To create a copy constructor in java, we need to first declare a constructor that takes an object of the same type as a parameter. For example: public class Student { private int roll ; private String name; // Declaring a copy constructor by passing the parameter as the class public Student( Student student ) { } }
  • 12. Creating a Copy Constructor in Java 12 • After declaring a copy constructor, we need to copy each field of the input object of the class into the new object. For example: public class Student { private int roll; private String name; // Copying each field of the existing object into the newly created object public Student( Student student ) { this.id = student.roll; this.name = student.name; } }
  • 13. Copy Constructor example 13 package Xyz; public class Student { private int roll; private String name; //constructor to initialize roll number and name of the student Student(int rollNo, String sName) { roll = rollNo; name = sName; } //copy constructor Student(Student student) { System.out.println("n---Copy Constructor Invoked---"); roll = student.roll; name = student.name; } //method to return roll number int printRoll() { return roll; } //Method to return name of the student String printName() { return name; } }
  • 14. Copy Constructor example 14 //class to create student object and print roll number and name of the student package Xyz; public class Xyz { public static void main(String[] args) { Student student1 = new Student(101, “ali"); System.out.println("Roll number of the first student: "+ student1.printRoll()); System.out.println("Name of the first student: "+ student1.printName()); //passing the parameter to the copy constructor Student student2 = new Student(student1); System.out.println("nRoll number of the second student: "+ student2.printRoll()); System.out.println("Name of the second student: "+ student2.printName()); } } Roll number of the first student: 101 Name of the first student: Ali —Copy Constructor Invoked— Roll number of the second student: 101 Name of the second student: Ali
  • 15. References 15 • https://beginnersbook.com/2013/05/constructor-overloading/ • https://www.codesdope.com/java-constructor-overloading/ • https://www.guru99.com/java-constructors.html • https://www.scientecheasy.com/2020/06/java-constructor- overloading.html/ • https://beginnersbook.com/2013/05/method-overloading/ • https://techvidvan.com/tutorials/java-constructor-chaining/