SlideShare a Scribd company logo
1 of 18
Download to read offline
Blue Ridge Public School
Standard X
Computer Applications – Chapter – 7 - Constructors
Blue
Ridge
Public
School
1
Topics
• What are Constructors?
• Need for Constructors
• Types of Constructors
• Parameterized Constructors
• Constructor Overloading
2
Blue
Ridge
Public
School
What are Constructors?
• A constructor in Java is a block of code similar to a method
that is called when an instance of an object is created
• It is a special method that is used to initialize a newly created
object
• Java constructor is invoked at the time of object creation
• It constructs the values i.e. provides data for the object that is
why it is known as constructor
3
Blue
Ridge
Public
School
What are Constructors – cont.
• Key differences between a constructor and a method
• A constructor doesn’t have a return type (not even void) since
the basic aim is to place the value in the object. If we write the
return type for the constructor then that constructor will be
treated as ordinary method
• The name of the constructor must be the same as the name of
the class
• Constructor definitions should not be static as constructors will
be called each and every time, whenever an object is created
4
Blue
Ridge
Public
School
What are Constructors – cont.
• Unlike methods, constructors are not considered members of a
class
• A constructor is called automatically when a new instance of an
object is created
5
Method Constructor
Method can be any user
defined name
Constructor must be class
name
Method should have return
type
It should not have any return
type (even void)
Method should be called
explicitly either with object
reference or class reference
It will be called automatically
whenever object is created
Method is not provided by
compiler in any case
The java compiler provides a
default constructor if we do
not have any constructor
Blue
Ridge
Public
School
Need for Constructors
• It can be cumbersome to initialize all variables in a call each
time an instance of a class in created
• Constructors are mainly created for initializing the object
• Initialization is a process of assigning user defined values at
the time of allocation of memory space
• An advantage of constructors in Java is it eliminates placing
the default values
6
Blue
Ridge
Public
School
Need for Constructors – cont.
• Whenever we create an object of any class, memory is
allocated memory for all the data members and their
values are initialized to their default values
• To eliminate these default values by user defined values
we use constructor
7
Blue
Ridge
Public
School
Constructor Example
class Programming
{ //constructor method
Programming()
{
System.out.println("Constructor method called.");
}
public static void main(String[] args)
{
Programming object = new Programming(); //creating object
}
}
8
Blue
Ridge
Public
School
Types of Constructors
• Based on creating objects in Java, constructor are classified in
two types. They are:
• Default or no argument Constructor
• Parameterized Constructor
9
Blue
Ridge
Public
School
Types of Constructors – cont.
 Default or no argument Constructor
• A constructor that has no parameter is known as default
constructor
• If we do not define a constructor in a class, then compiler
creates default constructor(with no arguments) for the class
• If we write a constructor with arguments or no-argument then
compiler does not create default constructor
Default constructor provides the default values to the object like
0, null etc. depending on the type
10
Blue
Ridge
Public
School
Types of Constructors – cont.
• Example of default constructor
• In this example, we are creating the no-argument constructor in
the Bike class
• It will be invoked at the time of object creation
class Bike
{
Bike()
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike b=new Bike ();
}
}
11
Blue
Ridge
Public
School
Types of Constructors – cont.
• If there is no constructor in a class, compiler automatically
creates a default constructor
• The default constructor is a constructor that the Java
compiler adds to your code if no explicit constructor is
available
• If you have added your own constructor (no matter whether
it's without parameters or with parameters) the compiler will
not add the default constructor in this case
12
Blue
Ridge
Public
School
Types of Constructors – cont.
• Parameterized Constructor
• A constructor that has parameters is known as parameterized
constructor
• If we want to initialize fields of the class with your own values,
then use parameterized constructor
• This type of constructor accepts parameters and initializes the
data members based on the arguments passed to it
• A parameter is a variable in a method definition. When a method is
called, the arguments are the data you pass into the method's
parameters
public void MyMethod(String myParam) { }
...
String myArg1 = "this is my argument"; myClass.MyMethod(myArg1);
13
Blue
Ridge
Public
School
Types of Constructors – cont.
• Example of parameterized constructor
class Student4{
int id;
String name;
Student4(int i,String n){
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[]){
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
• In this example, we have created the constructor of Student class that has two parameters
• We can have any number of parameters in the constructor
14
Constructor Overloading
• Constructor overloading is a technique in Java in which a class
can have any number of constructors that differ in parameter
lists
• Like methods, we can overload constructors for creating
objects in different ways
• Compiler differentiates constructors on the basis of numbers
of parameters, types of the parameters and order of the
parameters
15
Blue
Ridge
Public
School
Constructor Overloading – cont.
• Example of Constructor Overloading
class Student5{
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
16
Blue
Ridge
Public
School
Constructor Overloading – cont.
class Demo{
int value1;
int value2;
Demo(){
value1 = 10;
value2 = 20;
System.out.println("Inside 1st Constructor");
}
Demo(int a){
value1 = a;
System.out.println("Inside 2nd Constructor");
}
Demo(int a,int b){
value1 = a;
value2 = b;
System.out.println("Inside 3rd Constructor");
}
public void display(){
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
}
public static void main(String args[]){
Demo d1 = new Demo();
Demo d2 = new Demo(30);
Demo d3 = new Demo(30,40);
d1.display();
d2.display();
d3.display();
}
}
17
Output
Blue
Ridge
Public
School
Thank You!!
18
Blue
Ridge
Public
School

More Related Content

Similar to Chapter 7 - Constructors.pdf

CST 203 Lecture 7.pptx
CST 203 Lecture 7.pptxCST 203 Lecture 7.pptx
CST 203 Lecture 7.pptxDrKalkaDubey1
 
Constructors in java
Constructors in javaConstructors in java
Constructors in javachauhankapil
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptxEpsiba1
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and DestructorSunipa Bera
 
Constructor destructor.ppt
Constructor destructor.pptConstructor destructor.ppt
Constructor destructor.pptKarthik Sekar
 
Unit No 2 Objects and Classes.pptx
Unit No 2 Objects and Classes.pptxUnit No 2 Objects and Classes.pptx
Unit No 2 Objects and Classes.pptxDrYogeshDeshmukh1
 
Constructors in java
Constructors in javaConstructors in java
Constructors in javasunilchute1
 
C++ training
C++ training C++ training
C++ training PL Sharma
 
Constructor overloading & method overloading
Constructor overloading & method overloadingConstructor overloading & method overloading
Constructor overloading & method overloadinggarishma bhatia
 
UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptxakila m
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructorSaharsh Anand
 
Java 102 intro to object-oriented programming in java
Java 102   intro to object-oriented programming in javaJava 102   intro to object-oriented programming in java
Java 102 intro to object-oriented programming in javaagorolabs
 

Similar to Chapter 7 - Constructors.pdf (20)

CST 203 Lecture 7.pptx
CST 203 Lecture 7.pptxCST 203 Lecture 7.pptx
CST 203 Lecture 7.pptx
 
Constructors in java
Constructors in javaConstructors in java
Constructors in java
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
 
Constructor destructor.ppt
Constructor destructor.pptConstructor destructor.ppt
Constructor destructor.ppt
 
Unit No 2 Objects and Classes.pptx
Unit No 2 Objects and Classes.pptxUnit No 2 Objects and Classes.pptx
Unit No 2 Objects and Classes.pptx
 
BCA Class and Object (3).pptx
BCA Class and Object (3).pptxBCA Class and Object (3).pptx
BCA Class and Object (3).pptx
 
Constructors in java
Constructors in javaConstructors in java
Constructors in java
 
C++ training
C++ training C++ training
C++ training
 
Constructors in JAva.pptx
Constructors in JAva.pptxConstructors in JAva.pptx
Constructors in JAva.pptx
 
Oops
OopsOops
Oops
 
Constructor
ConstructorConstructor
Constructor
 
Constructor overloading & method overloading
Constructor overloading & method overloadingConstructor overloading & method overloading
Constructor overloading & method overloading
 
CPP15 - Inheritance
CPP15 - InheritanceCPP15 - Inheritance
CPP15 - Inheritance
 
UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptx
 
25csharp
25csharp25csharp
25csharp
 
25c
25c25c
25c
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
 
Java Constructor
Java ConstructorJava Constructor
Java Constructor
 
Java 102 intro to object-oriented programming in java
Java 102   intro to object-oriented programming in javaJava 102   intro to object-oriented programming in java
Java 102 intro to object-oriented programming in java
 

Recently uploaded

Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 

Recently uploaded (20)

Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 

Chapter 7 - Constructors.pdf

  • 1. Blue Ridge Public School Standard X Computer Applications – Chapter – 7 - Constructors Blue Ridge Public School 1
  • 2. Topics • What are Constructors? • Need for Constructors • Types of Constructors • Parameterized Constructors • Constructor Overloading 2 Blue Ridge Public School
  • 3. What are Constructors? • A constructor in Java is a block of code similar to a method that is called when an instance of an object is created • It is a special method that is used to initialize a newly created object • Java constructor is invoked at the time of object creation • It constructs the values i.e. provides data for the object that is why it is known as constructor 3 Blue Ridge Public School
  • 4. What are Constructors – cont. • Key differences between a constructor and a method • A constructor doesn’t have a return type (not even void) since the basic aim is to place the value in the object. If we write the return type for the constructor then that constructor will be treated as ordinary method • The name of the constructor must be the same as the name of the class • Constructor definitions should not be static as constructors will be called each and every time, whenever an object is created 4 Blue Ridge Public School
  • 5. What are Constructors – cont. • Unlike methods, constructors are not considered members of a class • A constructor is called automatically when a new instance of an object is created 5 Method Constructor Method can be any user defined name Constructor must be class name Method should have return type It should not have any return type (even void) Method should be called explicitly either with object reference or class reference It will be called automatically whenever object is created Method is not provided by compiler in any case The java compiler provides a default constructor if we do not have any constructor Blue Ridge Public School
  • 6. Need for Constructors • It can be cumbersome to initialize all variables in a call each time an instance of a class in created • Constructors are mainly created for initializing the object • Initialization is a process of assigning user defined values at the time of allocation of memory space • An advantage of constructors in Java is it eliminates placing the default values 6 Blue Ridge Public School
  • 7. Need for Constructors – cont. • Whenever we create an object of any class, memory is allocated memory for all the data members and their values are initialized to their default values • To eliminate these default values by user defined values we use constructor 7 Blue Ridge Public School
  • 8. Constructor Example class Programming { //constructor method Programming() { System.out.println("Constructor method called."); } public static void main(String[] args) { Programming object = new Programming(); //creating object } } 8 Blue Ridge Public School
  • 9. Types of Constructors • Based on creating objects in Java, constructor are classified in two types. They are: • Default or no argument Constructor • Parameterized Constructor 9 Blue Ridge Public School
  • 10. Types of Constructors – cont.  Default or no argument Constructor • A constructor that has no parameter is known as default constructor • If we do not define a constructor in a class, then compiler creates default constructor(with no arguments) for the class • If we write a constructor with arguments or no-argument then compiler does not create default constructor Default constructor provides the default values to the object like 0, null etc. depending on the type 10 Blue Ridge Public School
  • 11. Types of Constructors – cont. • Example of default constructor • In this example, we are creating the no-argument constructor in the Bike class • It will be invoked at the time of object creation class Bike { Bike() { System.out.println("Bike is created"); } public static void main(String args[]) { Bike b=new Bike (); } } 11 Blue Ridge Public School
  • 12. Types of Constructors – cont. • If there is no constructor in a class, compiler automatically creates a default constructor • The default constructor is a constructor that the Java compiler adds to your code if no explicit constructor is available • If you have added your own constructor (no matter whether it's without parameters or with parameters) the compiler will not add the default constructor in this case 12 Blue Ridge Public School
  • 13. Types of Constructors – cont. • Parameterized Constructor • A constructor that has parameters is known as parameterized constructor • If we want to initialize fields of the class with your own values, then use parameterized constructor • This type of constructor accepts parameters and initializes the data members based on the arguments passed to it • A parameter is a variable in a method definition. When a method is called, the arguments are the data you pass into the method's parameters public void MyMethod(String myParam) { } ... String myArg1 = "this is my argument"; myClass.MyMethod(myArg1); 13 Blue Ridge Public School
  • 14. Types of Constructors – cont. • Example of parameterized constructor class Student4{ int id; String name; Student4(int i,String n){ id = i; name = n; } void display() { System.out.println(id+" "+name); } public static void main(String args[]){ Student4 s1 = new Student4(111,"Karan"); Student4 s2 = new Student4(222,"Aryan"); s1.display(); s2.display(); } } • In this example, we have created the constructor of Student class that has two parameters • We can have any number of parameters in the constructor 14
  • 15. Constructor Overloading • Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter lists • Like methods, we can overload constructors for creating objects in different ways • Compiler differentiates constructors on the basis of numbers of parameters, types of the parameters and order of the parameters 15 Blue Ridge Public School
  • 16. Constructor Overloading – cont. • Example of Constructor Overloading class Student5{ int id; String name; int age; Student5(int i,String n){ id = i; name = n; } Student5(int i,String n,int a){ id = i; name = n; age=a; } void display(){System.out.println(id+" "+name+" "+age);} public static void main(String args[]){ Student5 s1 = new Student5(111,"Karan"); Student5 s2 = new Student5(222,"Aryan",25); s1.display(); s2.display(); } } 16 Blue Ridge Public School
  • 17. Constructor Overloading – cont. class Demo{ int value1; int value2; Demo(){ value1 = 10; value2 = 20; System.out.println("Inside 1st Constructor"); } Demo(int a){ value1 = a; System.out.println("Inside 2nd Constructor"); } Demo(int a,int b){ value1 = a; value2 = b; System.out.println("Inside 3rd Constructor"); } public void display(){ System.out.println("Value1 === "+value1); System.out.println("Value2 === "+value2); } public static void main(String args[]){ Demo d1 = new Demo(); Demo d2 = new Demo(30); Demo d3 = new Demo(30,40); d1.display(); d2.display(); d3.display(); } } 17 Output Blue Ridge Public School