SlideShare a Scribd company logo
1 of 34
Constructors and this
Types in Java





before discussing constructors, we need
to look briefly at data types in Java
in Java, every variable has a type
the assignment operator (=) is used to
assign values to variables

Constructors and this

2
Types in Java


the following statement declares
examGrade to be an int variable and
assigns examGrade a value of 93
int examGrade = 93;

Using Objects

3
Declaring and Initializing


the statement
int examGrade = 93;
could also be written as
int examGrade;
examGrade = 93;

Using Objects

declaration
assign value

4
Primitive Types


numbers in Java are examples of

primitive types


the variable examGrade does not
represent an object



int is not a class
int is a primitive type

Using Objects

5
Object Variables


object variables can be declared in the
same way as variables for primitive
types





Dog myDog;
String myString;

object variables differ from primitive
values in that they hold a reference to
an object, rather than the actual value
of the object

Using Objects

6
Reference Variables




examGrade is a variable that stores a
primitive type
myDog and myString are reference
variables
examGrade

myDog

myString

A Dog Object

"Hello World!"

93

Using Objects

7
The new Operator


use the new operator to create a new
object

Rectangle myBox = new Rectangle();




the number and type of parameters
determines the constructor to be called
note: the above statement would be
placed in a driver program; it would
invoke a constructor from the
Rectangle class

Constructors and this

8
The new Operator


when the new operator is used



memory is allocated for the object
attributes are assigned default values






false is assigned to boolean fields
0 is assigned to numeric fields
null is assigned to object references

the constructor is then called to do any
user-specified initialization

Constructors and this

9
Constructors


constructing a specific object is called

instantiation




the constructor normally initializes the
instance variables of the object
a class may have more than one
constructor

Constructors and this

10
Rectangle Constructors




let’s take another look at the
Rectangle class
if you look at the Java API for the
Rectangle class, you will find several
constructors, a couple of which are
shown on the next slide

Constructors and this

11
Rectangle Constructors


Rectangle(int x, int y, int w
idth, int height)




constructs a Rectangle with upper-left
corner at (x, y), with width and height as
specified by the last two parameters

Rectangle()


constructs a Rectangle with upper-left
corner at (0,0), and with width and height
of 0

Constructors and this

12
No-arg Constructors






the second constructor on the previous
slide has no parameters
such a constructor is called a no-arg
constructor
no-arg constructors are frequently used
to assign default values to the instance
variables

Constructors and this

13
No-arg Constructors


although not required, it is generally
advisable to supply a no-arg constructor
for any class you define

Constructors and this

14
The Default Constructor






it is permissible to define a class
without any constructors
for classes with no constructors Java
provides a no-arg constructor, called
the default constructor
the default constructor does nothing

Constructors and this

15
The Default Constructor




if you provide some constructors with
arguments, and you also want a no-arg
constructor, you must provide it
yourself
the default constructor provided by
Java is only available if no constructors
are provided in the class

Constructors and this

16
The new Operator Revisited


if no constructor is provided, except for
the default constructor, the new
operator creates a new object with the
default values assigned to the
attributes; then the default constructor
is called


the default constructor does nothing, but
new must invoke a constructor, so the
default constructor will be used if there is
no user-supplied constructor

Constructors and this

17
Constructing Strings


there are some shortcuts for String
objects that enable us to create strings
very easily





String myString = "Hello World!"
String myString2 = myString;

the previous statements result in two
String objects named myString and
myString2, both referencing the same
String object "Hello World!"

Using Objects

18
myString and myString2
myString

myString2

"Hello World!"

Using Objects

19
Invoking Methods






objects are normally created and used
in a driver program
when invoking a method from a driver
program you must supply an object
reference
otherwise the compiler will not be able
to determine which object is the
receiver object

Constructors and this

20
Example
public class
…
Dog zelda =
"Standard
Dog midge =
"Standard

Constructors and this

Driver
new Dog(
Poodle",
new Dog(
Poodle",

"Zelda",
7 );
“Midge",
5 );

21
Example
setAge( 9 );
System.out.println(getAge());
WRONG!
these method calls have no object reference; are we
trying to set and get the age for zelda or for midge?

zelda.setAge( 9 );
System.out.println(
zelda.getAge());
Do this instead -- use
an object reference
Constructors and this

22
Implicit and Explicit Parameters




in the example given above, zelda is
an explicit object reference to the
object whose setAge and getAge
methods are being invoked
inside a class definition, implicit
parameters may be used to refer to
instance variables and to invoke
methods

Constructors and this

23
Implicit Parameters
consider the following implementation
of the setAge method
public void setAge( int ageIn )
{
age = ageIn;
}


The private instance variable age must be associated
with an object, but there is no object reference given.
What object does age belong to?
Constructors and this

24
Implicit Parameters


let’s return to the call to setAge from
the driver program
zelda.setAge( 9 );

zelda is an explicit
object reference

Constructors and this

the argument 9 is an
explicit parameter

25
Implicit Parameters







this call invokes zelda’s setAge method
in the Dog class
inside the setAge method the
assignment statement is executed
age = ageIn;
zelda is the implicit parameter used
the age field belonging to the object
zelda is updated

Constructors and this

26
Implicit Parameters




when is it legal to use implicit
parameters?
when a main method creates an object
and then calls one of that object’s
methods, it must supply an object
reference, as in
zelda.setAge( 9 );

Constructors and this

27
Implicit Parameters




inside a class definition, if one method
invokes another method, an implicit
reference can be used
in this case, the implicit reference used
by the first method will also be used for
any method call made by the first
method

Constructors and this

28
The this Keyword




the implicit parameter used with a
method or private instance variable can
be accessed with the keyword this
for example, the body of the setAge
method could be written as
this.age = ageIn;

Constructors and this

29
this And Constructors




it is permissible to have one constructor
call another constructor
suppose we have a Dog class with the
two constructors shown on the next
slide

Constructors and this

30
this and Constructors
public Dog(String nameIn, String breedIn, int ageIn)
{
name = nameIn;
breed = breedIn;
age = ageIn;
}
public Dog()
{
name = "unknown";
breed = "unknown";
age = 0;
}

Constructors and this

31
this And Constructors


we can use the this keyword to
rewrite the no-arg constructor for the
Dog class
// no-arg constructor
public Dog()
{
this(“unknown“, “unknown“, 0);
}

Constructors and this

32
this And Constructors
the command
this(“unknown“, “unknown“, 0);


tells the compiler to call a constructor
with the appropriate signature and
supply the values of the arguments for
the parameters in the called constructor

Constructors and this

33
Constructors and this

The End

More Related Content

What's hot

What's hot (20)

Constructor and destructor
Constructor  and  destructor Constructor  and  destructor
Constructor and destructor
 
Constructors & destructors
Constructors & destructorsConstructors & destructors
Constructors & destructors
 
Constructor and destructor
Constructor and destructorConstructor and destructor
Constructor and destructor
 
Constructor
ConstructorConstructor
Constructor
 
constructor and destructor
constructor and destructorconstructor and destructor
constructor and destructor
 
Constructor
ConstructorConstructor
Constructor
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Tutconstructordes
TutconstructordesTutconstructordes
Tutconstructordes
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
constructor & destructor in cpp
constructor & destructor in cppconstructor & destructor in cpp
constructor & destructor in cpp
 
04. constructor & destructor
04. constructor & destructor04. constructor & destructor
04. constructor & destructor
 
Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)
 
Constructor and Destructor PPT
Constructor and Destructor PPTConstructor and Destructor PPT
Constructor and Destructor PPT
 
Tut Constructor
Tut ConstructorTut Constructor
Tut Constructor
 
Oop Constructor Destructors Constructor Overloading lecture 2
Oop Constructor  Destructors Constructor Overloading lecture 2Oop Constructor  Destructors Constructor Overloading lecture 2
Oop Constructor Destructors Constructor Overloading lecture 2
 
iOS Session-2
iOS Session-2iOS Session-2
iOS Session-2
 
Constructor overloading & method overloading
Constructor overloading & method overloadingConstructor overloading & method overloading
Constructor overloading & method overloading
 
Constructor in c++
Constructor in c++Constructor in c++
Constructor in c++
 
Op ps
Op psOp ps
Op ps
 

Similar to Constructors

08review (1)
08review (1)08review (1)
08review (1)IIUM
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfacesmadhavi patil
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxRAJASEKHARV10
 
Week9 Intro to classes and objects in Java
Week9 Intro to classes and objects in JavaWeek9 Intro to classes and objects in Java
Week9 Intro to classes and objects in Javakjkleindorfer
 
Constructors In Java – Unveiling Object Creation
Constructors In Java – Unveiling Object CreationConstructors In Java – Unveiling Object Creation
Constructors In Java – Unveiling Object CreationGeekster
 
Class & Object - Intro
Class & Object - IntroClass & Object - Intro
Class & Object - IntroPRN USM
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIEduardo Bergavera
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7Vince Vo
 
14review(abstract classandinterfaces)
14review(abstract classandinterfaces)14review(abstract classandinterfaces)
14review(abstract classandinterfaces)IIUM
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptxEpsiba1
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.pptDeepVala5
 

Similar to Constructors (20)

08review (1)
08review (1)08review (1)
08review (1)
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
 
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
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
JAVA CONCEPTS
JAVA CONCEPTS JAVA CONCEPTS
JAVA CONCEPTS
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptx
 
Creating classes and applications in java
Creating classes and applications in javaCreating classes and applications in java
Creating classes and applications in java
 
Week9 Intro to classes and objects in Java
Week9 Intro to classes and objects in JavaWeek9 Intro to classes and objects in Java
Week9 Intro to classes and objects in Java
 
Classes1
Classes1Classes1
Classes1
 
Lecture11.docx
Lecture11.docxLecture11.docx
Lecture11.docx
 
Constructors In Java – Unveiling Object Creation
Constructors In Java – Unveiling Object CreationConstructors In Java – Unveiling Object Creation
Constructors In Java – Unveiling Object Creation
 
Class & Object - Intro
Class & Object - IntroClass & Object - Intro
Class & Object - Intro
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
 
14review(abstract classandinterfaces)
14review(abstract classandinterfaces)14review(abstract classandinterfaces)
14review(abstract classandinterfaces)
 
00-review.ppt
00-review.ppt00-review.ppt
00-review.ppt
 
Reflection
ReflectionReflection
Reflection
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.ppt
 

Recently uploaded

Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
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
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
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
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
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
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 

Recently uploaded (20)

Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
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
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
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
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
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
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 

Constructors

  • 2. Types in Java    before discussing constructors, we need to look briefly at data types in Java in Java, every variable has a type the assignment operator (=) is used to assign values to variables Constructors and this 2
  • 3. Types in Java  the following statement declares examGrade to be an int variable and assigns examGrade a value of 93 int examGrade = 93; Using Objects 3
  • 4. Declaring and Initializing  the statement int examGrade = 93; could also be written as int examGrade; examGrade = 93; Using Objects declaration assign value 4
  • 5. Primitive Types  numbers in Java are examples of primitive types  the variable examGrade does not represent an object   int is not a class int is a primitive type Using Objects 5
  • 6. Object Variables  object variables can be declared in the same way as variables for primitive types    Dog myDog; String myString; object variables differ from primitive values in that they hold a reference to an object, rather than the actual value of the object Using Objects 6
  • 7. Reference Variables   examGrade is a variable that stores a primitive type myDog and myString are reference variables examGrade myDog myString A Dog Object "Hello World!" 93 Using Objects 7
  • 8. The new Operator  use the new operator to create a new object Rectangle myBox = new Rectangle();   the number and type of parameters determines the constructor to be called note: the above statement would be placed in a driver program; it would invoke a constructor from the Rectangle class Constructors and this 8
  • 9. The new Operator  when the new operator is used   memory is allocated for the object attributes are assigned default values     false is assigned to boolean fields 0 is assigned to numeric fields null is assigned to object references the constructor is then called to do any user-specified initialization Constructors and this 9
  • 10. Constructors  constructing a specific object is called instantiation   the constructor normally initializes the instance variables of the object a class may have more than one constructor Constructors and this 10
  • 11. Rectangle Constructors   let’s take another look at the Rectangle class if you look at the Java API for the Rectangle class, you will find several constructors, a couple of which are shown on the next slide Constructors and this 11
  • 12. Rectangle Constructors  Rectangle(int x, int y, int w idth, int height)   constructs a Rectangle with upper-left corner at (x, y), with width and height as specified by the last two parameters Rectangle()  constructs a Rectangle with upper-left corner at (0,0), and with width and height of 0 Constructors and this 12
  • 13. No-arg Constructors    the second constructor on the previous slide has no parameters such a constructor is called a no-arg constructor no-arg constructors are frequently used to assign default values to the instance variables Constructors and this 13
  • 14. No-arg Constructors  although not required, it is generally advisable to supply a no-arg constructor for any class you define Constructors and this 14
  • 15. The Default Constructor    it is permissible to define a class without any constructors for classes with no constructors Java provides a no-arg constructor, called the default constructor the default constructor does nothing Constructors and this 15
  • 16. The Default Constructor   if you provide some constructors with arguments, and you also want a no-arg constructor, you must provide it yourself the default constructor provided by Java is only available if no constructors are provided in the class Constructors and this 16
  • 17. The new Operator Revisited  if no constructor is provided, except for the default constructor, the new operator creates a new object with the default values assigned to the attributes; then the default constructor is called  the default constructor does nothing, but new must invoke a constructor, so the default constructor will be used if there is no user-supplied constructor Constructors and this 17
  • 18. Constructing Strings  there are some shortcuts for String objects that enable us to create strings very easily    String myString = "Hello World!" String myString2 = myString; the previous statements result in two String objects named myString and myString2, both referencing the same String object "Hello World!" Using Objects 18
  • 20. Invoking Methods    objects are normally created and used in a driver program when invoking a method from a driver program you must supply an object reference otherwise the compiler will not be able to determine which object is the receiver object Constructors and this 20
  • 21. Example public class … Dog zelda = "Standard Dog midge = "Standard Constructors and this Driver new Dog( Poodle", new Dog( Poodle", "Zelda", 7 ); “Midge", 5 ); 21
  • 22. Example setAge( 9 ); System.out.println(getAge()); WRONG! these method calls have no object reference; are we trying to set and get the age for zelda or for midge? zelda.setAge( 9 ); System.out.println( zelda.getAge()); Do this instead -- use an object reference Constructors and this 22
  • 23. Implicit and Explicit Parameters   in the example given above, zelda is an explicit object reference to the object whose setAge and getAge methods are being invoked inside a class definition, implicit parameters may be used to refer to instance variables and to invoke methods Constructors and this 23
  • 24. Implicit Parameters consider the following implementation of the setAge method public void setAge( int ageIn ) { age = ageIn; }  The private instance variable age must be associated with an object, but there is no object reference given. What object does age belong to? Constructors and this 24
  • 25. Implicit Parameters  let’s return to the call to setAge from the driver program zelda.setAge( 9 ); zelda is an explicit object reference Constructors and this the argument 9 is an explicit parameter 25
  • 26. Implicit Parameters     this call invokes zelda’s setAge method in the Dog class inside the setAge method the assignment statement is executed age = ageIn; zelda is the implicit parameter used the age field belonging to the object zelda is updated Constructors and this 26
  • 27. Implicit Parameters   when is it legal to use implicit parameters? when a main method creates an object and then calls one of that object’s methods, it must supply an object reference, as in zelda.setAge( 9 ); Constructors and this 27
  • 28. Implicit Parameters   inside a class definition, if one method invokes another method, an implicit reference can be used in this case, the implicit reference used by the first method will also be used for any method call made by the first method Constructors and this 28
  • 29. The this Keyword   the implicit parameter used with a method or private instance variable can be accessed with the keyword this for example, the body of the setAge method could be written as this.age = ageIn; Constructors and this 29
  • 30. this And Constructors   it is permissible to have one constructor call another constructor suppose we have a Dog class with the two constructors shown on the next slide Constructors and this 30
  • 31. this and Constructors public Dog(String nameIn, String breedIn, int ageIn) { name = nameIn; breed = breedIn; age = ageIn; } public Dog() { name = "unknown"; breed = "unknown"; age = 0; } Constructors and this 31
  • 32. this And Constructors  we can use the this keyword to rewrite the no-arg constructor for the Dog class // no-arg constructor public Dog() { this(“unknown“, “unknown“, 0); } Constructors and this 32
  • 33. this And Constructors the command this(“unknown“, “unknown“, 0);  tells the compiler to call a constructor with the appropriate signature and supply the values of the arguments for the parameters in the called constructor Constructors and this 33