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

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
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 
SoftTeco - Software Development Company Profile
SoftTeco - Software Development Company ProfileSoftTeco - Software Development Company Profile
SoftTeco - Software Development Company Profileakrivarotava
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...OnePlan Solutions
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxRTS corp
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITmanoharjgpsolutions
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesVictoriaMetrics
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 
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
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 

Último (20)

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
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 
SoftTeco - Software Development Company Profile
SoftTeco - Software Development Company ProfileSoftTeco - Software Development Company Profile
SoftTeco - Software Development Company Profile
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh IT
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 Updates
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 
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...
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 

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