SlideShare uma empresa Scribd logo
1 de 7
Constructors 
• When you instantiated an object of a class, say A, I used 
the syntax A objName=new A(); 
• The first thing that occurs to you is, what is A()? 
• Well, it’s a special type of, well, you may say, methods, 
which has the features like…. 
1. It has no return type not even void 
2. It can’t be called without the operator ‘new’ 
3. As you might have seen but not noticed, it has the same 
name as that of the class. 
4. It can’t be static. 
5. It can be overloaded as any other method. i.e. it can have 
sohamsengupta@yahoo.com1 
arguments 
6. Any method with some return type may have same name 
as that of the class, but that’s not the constructor.
Execution order of constructors 
• Assume the program below… 
class A 
{ 
A(){ 
System.out.println(“From contstructor”); 
} 
public static void main(String[] args){ 
A a=new A(); 
} 
} 
Output: From Constructor 
sohamsengupta@yahoo.com2
Before I say more on order of execution, I 
spend some time on Types of Constructors 
• Constructors are roughly of 2 types… No-argument constructors and 
argument-constructors. 
• Caution: No-argument constructors are not necessarily the default 
constructor. Default constructor is the no-argument constructor 
provided by the compiler should the developer give none. 
• Once you declare at least one argument-constructor inside your class, 
your no-argument default constructor would not be available at all 
until you yourself provide your no-argument constructor. 
• Copy constructor is a special type of argument constructor where the 
argument is an object of the same class. Examples follow on the next 
slide 
sohamsengupta@yahoo.com3
Examples on Constructor 
sohamsengupta@yahoo.com4 
class A 
{ 
A(int x){ 
System.out.println(“H”); 
} 
} 
If you write a code like 
A objName=new A(); // 
Error 
Since no-arg constructor is 
no more available. Use 
A objName=new A(940); 
If you must need a no-arg 
constructor, you must 
either omit arg-ed ones or 
simply give one no-arg 
constructor 
In your code performing as 
per your desired taks. 
class A 
{ 
int x; 
A(A objRef){ 
this.x=objRef.x; 
} 
} 
It’s a copy constructor. It 
takes as argument an 
object of the same class and 
initializes the instance 
value accordingly. 
Since it can perform the 
job of copying data 
members, it’s named 
“Copy” 
It can, however perform 
other tasks. It’s not 
mandatory that you always 
do the task of copying…. U 
can anything even nothing 
within a copy constructor. 
class A 
{ 
int x,y; 
A(int a){ 
this.x=this.y=a; 
} 
A(int x,int y){ 
this.x=x; 
this.y=y; 
} 
} 
Thus constructors give the 
developer a way to 
initialize the data members. 
Remember constructors do 
not do initialization by 
themselves.
Now it’s time to know when a constructor is actually called 
• Rule: In a class, all the static blocks and 
initializers are executed first once and only once in 
the order in which they appear in the code, when 
the class is loaded into the memory. 
• Then non-static blocks, often known as instance 
blocks and initializers are executed in the order in 
which they appear. They are execute for each 
object creation. Instance fields are allocated into 
memory with corresponding default values. 
• Then constructor is called and inside the 
constructor the call to super(<>) must be the first 
statement. Well, more on super later 
sohamsengupta@yahoo.com5
See the example & ponder over the outcome 
class B 
{ 
B(){ 
System.out.println("Constructor"); 
} 
{ 
System.out.println("Non-static block 1"); 
sohamsengupta@yahoo.com6 
} static{ 
System.out.println("static block 1"); 
} static{ 
System.out.println("static block 2"); 
} 
public static void main(String[] soham){ 
B b1=new B(); 
B b2=new B(); 
}{ 
System.out.println("Non-static block 2"); 
}} 
static block 1 
static block 2 
Non-static block 1 
Non-static block 2 
Constructor 
Non-static block 1 
Non-static block 2 
Constructor 
For the first object, when 
the class B is loaded into 
memory, static blocks are 
executed in their order. 
This is only once. Then for 
each object, first non-static 
blocks are executed in 
order then the constructor
To-Do’s 
• Involve in the 
Program of Addition 
of Complex Numbers 
constructors with 
arguments. 
• Refer to any book for 
“chaining” of 
constructors. 
• In case of chaining, 
this() must be the first 
statement is a 
constructor 
• Remember, like static 
methods, static blocks 
can’t access non-static 
data and methods. 
• “this” cannot be used 
from within a static 
context, i.e. a static 
method or static block 
and no values can be 
assigned to “this” as 
this is final 
sohamsengupta@yahoo.com7

Mais conteúdo relacionado

Mais procurados

Constructor and destructor
Constructor and destructorConstructor and destructor
Constructor and destructorrajshreemuthiah
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handlingsanya6900
 
Java8: what's new and what's hot
Java8: what's new and what's hotJava8: what's new and what's hot
Java8: what's new and what's hotSergii Maliarov
 
ConsTRUCTION AND DESTRUCTION
ConsTRUCTION AND DESTRUCTIONConsTRUCTION AND DESTRUCTION
ConsTRUCTION AND DESTRUCTIONShweta Shah
 
Constructor & destructor based question- cbse cs class 12th
Constructor & destructor based question-  cbse cs class 12thConstructor & destructor based question-  cbse cs class 12th
Constructor & destructor based question- cbse cs class 12thAAKASH KUMAR
 
Scaffolding with JMock
Scaffolding with JMockScaffolding with JMock
Scaffolding with JMockValerio Maggio
 
2CPP08 - Overloading and Overriding
2CPP08 - Overloading and Overriding2CPP08 - Overloading and Overriding
2CPP08 - Overloading and OverridingMichael Heron
 
Python advanced 1.handle error, generator, decorator and decriptor
Python advanced 1.handle error, generator, decorator and decriptor Python advanced 1.handle error, generator, decorator and decriptor
Python advanced 1.handle error, generator, decorator and decriptor John(Qiang) Zhang
 
Java Static Factory Methods
Java Static Factory MethodsJava Static Factory Methods
Java Static Factory MethodsYe Win
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScriptinjulkarnilesh
 

Mais procurados (20)

Tut Constructor
Tut ConstructorTut Constructor
Tut Constructor
 
C# Constructors
C# ConstructorsC# Constructors
C# Constructors
 
Computer programming 2 chapter 1-lesson 2
Computer programming 2  chapter 1-lesson 2Computer programming 2  chapter 1-lesson 2
Computer programming 2 chapter 1-lesson 2
 
Linq inside out
Linq inside outLinq inside out
Linq inside out
 
Constructor and destructor
Constructor and destructorConstructor and destructor
Constructor and destructor
 
C# Method overloading
C# Method overloadingC# Method overloading
C# Method overloading
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handling
 
Java8: what's new and what's hot
Java8: what's new and what's hotJava8: what's new and what's hot
Java8: what's new and what's hot
 
ConsTRUCTION AND DESTRUCTION
ConsTRUCTION AND DESTRUCTIONConsTRUCTION AND DESTRUCTION
ConsTRUCTION AND DESTRUCTION
 
Constructor & destructor based question- cbse cs class 12th
Constructor & destructor based question-  cbse cs class 12thConstructor & destructor based question-  cbse cs class 12th
Constructor & destructor based question- cbse cs class 12th
 
Method overloading and constructor overloading in java
Method overloading and constructor overloading in javaMethod overloading and constructor overloading in java
Method overloading and constructor overloading in java
 
Scaffolding with JMock
Scaffolding with JMockScaffolding with JMock
Scaffolding with JMock
 
Csharp
CsharpCsharp
Csharp
 
2CPP08 - Overloading and Overriding
2CPP08 - Overloading and Overriding2CPP08 - Overloading and Overriding
2CPP08 - Overloading and Overriding
 
11. java methods
11. java methods11. java methods
11. java methods
 
Python advanced 1.handle error, generator, decorator and decriptor
Python advanced 1.handle error, generator, decorator and decriptor Python advanced 1.handle error, generator, decorator and decriptor
Python advanced 1.handle error, generator, decorator and decriptor
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
 
Js
JsJs
Js
 
Java Static Factory Methods
Java Static Factory MethodsJava Static Factory Methods
Java Static Factory Methods
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 

Semelhante a Core java day4

Semelhante a Core java day4 (20)

25csharp
25csharp25csharp
25csharp
 
25c
25c25c
25c
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
 
Java Constructor
Java ConstructorJava Constructor
Java Constructor
 
Oops
OopsOops
Oops
 
Constructor destructor.ppt
Constructor destructor.pptConstructor destructor.ppt
Constructor destructor.ppt
 
Constructor
ConstructorConstructor
Constructor
 
Constructor & Destructor
Constructor & DestructorConstructor & Destructor
Constructor & Destructor
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
 
Lecture22.23.07.2014
Lecture22.23.07.2014Lecture22.23.07.2014
Lecture22.23.07.2014
 
Constructor and destructor in C++
Constructor and destructor in C++Constructor and destructor in C++
Constructor and destructor in C++
 
Constructors and destructors in C++ part 2
Constructors and destructors in C++ part 2Constructors and destructors in C++ part 2
Constructors and destructors in C++ part 2
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
BCA Class and Object (3).pptx
BCA Class and Object (3).pptxBCA Class and Object (3).pptx
BCA Class and Object (3).pptx
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
 
Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
 
Classes, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaClasses, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with Java
 
Chap2 class,objects contd
Chap2 class,objects contdChap2 class,objects contd
Chap2 class,objects contd
 
Constructors and destructors in C++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++
 

Mais de Soham Sengupta (20)

Spring method-level-secuirty
Spring method-level-secuirtySpring method-level-secuirty
Spring method-level-secuirty
 
Spring security mvc-1
Spring security mvc-1Spring security mvc-1
Spring security mvc-1
 
JavaScript event handling assignment
JavaScript  event handling assignment JavaScript  event handling assignment
JavaScript event handling assignment
 
Networking assignment 2
Networking assignment 2Networking assignment 2
Networking assignment 2
 
Networking assignment 1
Networking assignment 1Networking assignment 1
Networking assignment 1
 
Sohams cryptography basics
Sohams cryptography basicsSohams cryptography basics
Sohams cryptography basics
 
Network programming1
Network programming1Network programming1
Network programming1
 
JSR-82 Bluetooth tutorial
JSR-82 Bluetooth tutorialJSR-82 Bluetooth tutorial
JSR-82 Bluetooth tutorial
 
Xmpp and java
Xmpp and javaXmpp and java
Xmpp and java
 
Core java day2
Core java day2Core java day2
Core java day2
 
Core java day1
Core java day1Core java day1
Core java day1
 
Core java day5
Core java day5Core java day5
Core java day5
 
Exceptions
ExceptionsExceptions
Exceptions
 
Java.lang.object
Java.lang.objectJava.lang.object
Java.lang.object
 
Jsp1
Jsp1Jsp1
Jsp1
 
Soham web security
Soham web securitySoham web security
Soham web security
 
Html tables and_javascript
Html tables and_javascriptHtml tables and_javascript
Html tables and_javascript
 
Html javascript
Html javascriptHtml javascript
Html javascript
 
Java script
Java scriptJava script
Java script
 
Sohamsg ajax
Sohamsg ajaxSohamsg ajax
Sohamsg ajax
 

Último

Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 

Último (20)

Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 

Core java day4

  • 1. Constructors • When you instantiated an object of a class, say A, I used the syntax A objName=new A(); • The first thing that occurs to you is, what is A()? • Well, it’s a special type of, well, you may say, methods, which has the features like…. 1. It has no return type not even void 2. It can’t be called without the operator ‘new’ 3. As you might have seen but not noticed, it has the same name as that of the class. 4. It can’t be static. 5. It can be overloaded as any other method. i.e. it can have sohamsengupta@yahoo.com1 arguments 6. Any method with some return type may have same name as that of the class, but that’s not the constructor.
  • 2. Execution order of constructors • Assume the program below… class A { A(){ System.out.println(“From contstructor”); } public static void main(String[] args){ A a=new A(); } } Output: From Constructor sohamsengupta@yahoo.com2
  • 3. Before I say more on order of execution, I spend some time on Types of Constructors • Constructors are roughly of 2 types… No-argument constructors and argument-constructors. • Caution: No-argument constructors are not necessarily the default constructor. Default constructor is the no-argument constructor provided by the compiler should the developer give none. • Once you declare at least one argument-constructor inside your class, your no-argument default constructor would not be available at all until you yourself provide your no-argument constructor. • Copy constructor is a special type of argument constructor where the argument is an object of the same class. Examples follow on the next slide sohamsengupta@yahoo.com3
  • 4. Examples on Constructor sohamsengupta@yahoo.com4 class A { A(int x){ System.out.println(“H”); } } If you write a code like A objName=new A(); // Error Since no-arg constructor is no more available. Use A objName=new A(940); If you must need a no-arg constructor, you must either omit arg-ed ones or simply give one no-arg constructor In your code performing as per your desired taks. class A { int x; A(A objRef){ this.x=objRef.x; } } It’s a copy constructor. It takes as argument an object of the same class and initializes the instance value accordingly. Since it can perform the job of copying data members, it’s named “Copy” It can, however perform other tasks. It’s not mandatory that you always do the task of copying…. U can anything even nothing within a copy constructor. class A { int x,y; A(int a){ this.x=this.y=a; } A(int x,int y){ this.x=x; this.y=y; } } Thus constructors give the developer a way to initialize the data members. Remember constructors do not do initialization by themselves.
  • 5. Now it’s time to know when a constructor is actually called • Rule: In a class, all the static blocks and initializers are executed first once and only once in the order in which they appear in the code, when the class is loaded into the memory. • Then non-static blocks, often known as instance blocks and initializers are executed in the order in which they appear. They are execute for each object creation. Instance fields are allocated into memory with corresponding default values. • Then constructor is called and inside the constructor the call to super(<>) must be the first statement. Well, more on super later sohamsengupta@yahoo.com5
  • 6. See the example & ponder over the outcome class B { B(){ System.out.println("Constructor"); } { System.out.println("Non-static block 1"); sohamsengupta@yahoo.com6 } static{ System.out.println("static block 1"); } static{ System.out.println("static block 2"); } public static void main(String[] soham){ B b1=new B(); B b2=new B(); }{ System.out.println("Non-static block 2"); }} static block 1 static block 2 Non-static block 1 Non-static block 2 Constructor Non-static block 1 Non-static block 2 Constructor For the first object, when the class B is loaded into memory, static blocks are executed in their order. This is only once. Then for each object, first non-static blocks are executed in order then the constructor
  • 7. To-Do’s • Involve in the Program of Addition of Complex Numbers constructors with arguments. • Refer to any book for “chaining” of constructors. • In case of chaining, this() must be the first statement is a constructor • Remember, like static methods, static blocks can’t access non-static data and methods. • “this” cannot be used from within a static context, i.e. a static method or static block and no values can be assigned to “this” as this is final sohamsengupta@yahoo.com7