SlideShare a Scribd company logo
1 of 48
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
C HA PT E R 6
A Second
Lookat
Classes and
Objects
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Topics
Static Class Members
Overloaded Methods
Overloaded Constructors
Passing Objects as Arguments to Methods
Returning Objects from Methods
The toString method
Writing an equals method
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Topics (cont’d)
Methods that copy objects
Aggregation
The this Reference Variable
Inner Classes
Enumerated types
Garbage Collection
Object collaboration
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Review of Instance Fields and
Methods
Each instance of a class has its own copy of
instance variables.
Example:
The Rectangle class defines a length and a width field.
Each instance of the Rectangle class can have different
values stored in its length and width fields.
Instance methods require that an instance of
a class be created in order to be used.
Instance methods typically interact with
instance fields or calculate values based on
those fields.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Static Class Members
Static fields and static methods do not
belong to a single instance of a class.
To invoke a static method or use a
static field, the class name, rather than
the instance name, is used.
Example:
double val = Math.sqrt(25.0);
Class name Static method
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Static Fields
Class fields are declared using the static keyword
between the access specifier and the field type.
private static int instanceCount = 0;
The field is initialized to 0 only once, regardless of
the number of times the class is instantiated.
Primitive static fields are initialized to 0 if no
initialization is performed.
Examples: Countable.java, StaticDemo.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Static Fields
instanceCount field
(static)
3
Object1 Object3Object2
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Static Methods
Methods can also be declared static by placing the
static keyword between the access modifier and
the return type of the method.
public static double milesToKilometers(double miles)
{…}
When a class contains a static method, it is not
necessary to create an instance of the class in order
to use the method.
double kilosPerMile = Metric.milesToKilometers(1.0);
Examples: Metric.java, MetricDemo.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Static Methods
Static methods are convenient because
they may be called at the class level.
They are typically used to create utility
classes, such as the Math class in the
Java Standard Library.
Static methods may not communicate
with instance fields, only static fields.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Overloaded Methods
Two or more methods in a class may have the same name;
however, their parameter lists must be different.
public class MyMath{
public static int square(int number){
return number * number;
}
public static double square(double number){
return number * number;
}
}
Example: OverloadingDemo.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Overloaded Methods
Java uses the method signature (name,
type of parameters and order of
parameters) to determine which
method to call.
This process is known as binding.
The return type of the method is not
part of the method signature.
Example: Pay.java, WeeklyPay.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Overloaded Constructors
Class constructors are also methods.
This means that they can also be overloaded.
Overloading constructors gives
programmers more than one way to
construct an object of that class.
All of the previous restrictions on
overloading apply to constructors as well.
Example: Rectangle.java, TwoRectangles.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Revisiting The Default
Constructor
Java automatically provides a default
constructor for a class if a constructor
is not explicitly written.
The default constructor provided by
Java:
sets all numeric instance fields to 0
sets all char instance fields to ' ' (empty char)
sets all reference instance fields to null
sets all boolean instance fields to false
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Revisiting The Default
Constructor
We, as programmers, can provide a no-
arg constructor. This is a constructor
that accepts no arguments.
If a constructor that accepts arguments
is written, we should also write a no-
arg constructor.
If we write a no-arg constructor, we
should provide the initialization of all
instance fields.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Revisiting The Default
Constructor
InventoryItem
- description : String
- units : int
+ InventoryItem() :
+ InventoryItem(d : String) :
+ InventoryItem(d : String, u : int) :
+ setDescription(d : String) : void
+ setUnits(u : int) : void
+ getDescription() : String
+ getUnits() : int
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Passing Objects as
Arguments
Objects can be passed to methods as arguments.
Java passes all arguments by value.
When an object is passed as an argument, the value of the
reference variable is passed.
The value of the reference variable is an address or
reference to the object in memory.
A copy of the object is not passed, just a pointer to the
object.
When a method receives a reference variable as an
argument, it is possible for the method to modify the
contents of the object referenced by the variable.
Example: Dealer.java, Player.java, ChoHan.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Passing Objects as
ArgumentsExamples:
PassObject.java
PassObject2.java
displayRectangle(box);
public static void displayRectangle(Rectangle r)
{
// Display the length and width.
System.out.println("Length: " + r.getLength() +
" Width: " + r.getWidth());
}
A Rectangle object
length:
width:
12.0
5.0
Address
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Returning References From
Methods
Methods are not limited to returning the primitive
data types.
Methods can return references to objects as well.
Just as with passing parameters, a copy of the
object is not returned, only its address.
Example: ReturnObject.java
Method return type:
public static InventoryItem getData()
{
…
return new InventoryItem(d, u);
}
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Returning Objects from
Methodsitem = getData();
public static InventoryItem getData()
{
…
return new InventoryItem(d, u);
}
description:
units:
Pliers
address
A InventoryItem Object
25
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The toString Method
The toString method of a class can be
called explicitly:
Stock xyzCompany = new Stock ("XYZ", 9.62);
System.out.println(xyzCompany.toString());
However, the toString method does not
have to be called explicitly but is called
implicitly whenever you pass an object of the
class to println or print.
Stock xyzCompany = new Stock ("XYZ", 9.62);
System.out.println(xyzCompany);
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The toString method
The toString method is also called
implicitly whenever you concatenate an
object of the class with a string.
Stock xyzCompany = new Stock ("XYZ", 9.62);
System.out.println("The stock data is:n" +
xyzCompany);
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The toString Method
All objects have a toString method that returns
the class name and a hash of the memory address
of the object.
We can override the default method with our own
to print out more useful information.
Examples: Stock.java, StockDemo1.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The equals Method
When the == operator is used with reference
variables, the memory address of the objects
are compared.
The contents of the objects are not
compared.
All objects have an equals method.
The default operation of the equals method
is to compare memory addresses of the
objects (just like the == operator).
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The equals Method
The Stock class has an equals method.
If we try the following:
Stock stock1 = new Stock("GMX", 55.3);
Stock stock2 = new Stock("GMX", 55.3);
if (stock1 == stock2) // This is a mistake!
System.out.println("The objects are the same.");
else
System.out.println("The objects are not the same.");
only the addresses of the objects are compared
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The equals Method
Compare objects by their contents rather than by their memory
addresses.
Instead of simply using the == operator to compare two Stock
objects, we should use the equals method.
public boolean equals(Stock object2)
{
boolean status;
if(symbol.equals(Object2.symbol) &&
sharePrice == Object2.sharePrice)
status = true;
else
status = false;
return status;
}
See example: StockCompare.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Methods That Copy Objects
There are two ways to copy an object.
You cannot use the assignment operator to
copy reference types
Reference only copy
This is simply copying the address of an object into
another reference variable.
Deep copy (correct)
This involves creating a new instance of the class
and copying the values from one object into the
new object.
Example: ObjectCopy.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Copy Constructors
A copy constructor accepts an existing object of the
same class and clones it.
public Stock(Stock object 2)
{
symbol = object2.symbol;
sharePrice = object2.sharePrice;
}
// Create a Stock object
Stock company1 = new Stock("XYZ", 9.62);
//Create company2, a copy of company1
Stock company2 = new Stock(company1);
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Aggregation
Creating an instance of one class as a
reference in another class is called
object aggregation.
Aggregation creates a “has a”
relationship between objects.
Examples:
Instructor.java, Textbook.java, Course.java, CourseDemo.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Aggregation in UML Diagrams
Course
- courseName : String
- Instructor : Instructor
- textBook : TextBook
+ Course(name : String, instr : Instructor, text : TextBook)
+ getName() : String
+ getInstructor() : Instructor
+ getTextBook() : TextBook
+ toString() : String
TextBook
- title : String
- author : String
- publisher : String
+ TextBook(title : String, author : String,
publisher : String)
+ TextBook(object2 : TextBook)
+ set(title : String, author : String,
publisher : String) : void
+ toString() : String
Instructor
- lastName : String
- firstName : String
- officeNumber : String
+ Instructor(lname : String, fname : String,
office : String)
+Instructor(object2 : Instructor)
+set(lname : String, fname : String,
office : String): void
+ toString() : String
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Returning References to
Private Fields
• Avoid returning references to private
data elements.
• Returning references to private
variables will allow any object that
receives the reference to modify the
variable.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Null References
A null reference is a reference variable that points to
nothing.
If a reference is null, then no operations can be
performed on it.
References can be tested to see if they point to null
prior to being used.
if(name != null)
System.out.println("Name is: " +
name.toUpperCase());
Examples: FullName.java, NameTester.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The this Reference
The this reference is simply a name that an object
can use to refer to itself.
The this reference can be used to overcome
shadowing and allow a parameter to have the same
name as an instance field.
public void setFeet(int feet)
{
this.feet = feet;
//sets the this instance’s feet field
//equal to the parameter feet.
}
Local parameter variable
Shadowed instance variable
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The this Reference
The this reference can be used to call a constructor from
another constructor.
public Stock(String sym)
{
this(sym, 0.0);
}
This constructor would allow an instance of the Stock class to be
created using only the symbol name as a parameter.
It calls the constructor that takes the symbol and the price, using
sym as the symbol argument and 0 as the price argument.
Elaborate constructor chaining can be created using this
technique.
If this is used in a constructor, it must be the first statement in
the constructor.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Inner Classes
Classes my have other classes nested within
them.
These inner classes have unique properties.
An outer class can access the public
members of an inner class.
An inner class is not visible or accessible to
code outside the outer class.
An inner class can access the private
members of the outer class.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Inner Classes
Inner classes are defined inside the outer class.
Compiled byte code for inner classes is stored in a
separate file.
The file’s name consists of:
the name of the outer class
followed by a $ character
followed by the name of the inner class
followed by .class
RetailItem$CostData.class
Example: RetailItem.java, InnerClassDemo.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Enumerated Types
Known as an enum
Requires declaration and definition like a class
Syntax:
enum typeName { one or more enum constants }
Definition:
enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY }
– Declaration:
Day WorkDay; // creates a Day enum
Assignment:
Day WorkDay = Day.WEDNESDAY;
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Enumerated Types
An enum is a specialized class
Day.MONDAY
Day.TUESDAY
Day.WEDNESDAY
Day.SUNDAY
Day.THURSDAY
Day.FRIDAY
Day.SATURDAY
address
Each are objects of type Day, a specialized class
Day workDay = Day.WEDNESDAY;
The workDay variable holds the address of
the Day.WEDNESDAY object
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Enumerated Types - Methods
toString – returns name of calling constant
ordinal – returns the zero-based position of the constant in
the enum. For example the ordinal for Day.THURSDAY is 4
equals – accepts an object as an argument and returns true if
the argument is equal to the calling enum constant
compareTo - accepts an object as an argument and returns a
negative integer if the calling constant’s ordinal < than the
argument’s ordinal, a positive integer if the calling constant’s
ordinal > than the argument’s ordinal and zero if the calling
constant’s ordinal == the argument’s ordinal.
Examples:
EnumDemo.java, CarType.java, SportsCar.java, SportsCarDemo.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Enumerated Types -
Switching
Java allows you to test an enum constant with
a switch statement.
Example: SportsCarDemo2.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Garbage Collection
When objects are no longer needed
they should be destroyed.
This frees up the memory that they
consumed.
Java handles all of the memory
operations for you.
Simply set the reference to null and
Java will reclaim the memory.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Garbage Collection
The Java Virtual Machine has a process that runs in
the background that reclaims memory from released
objects.
The garbage collector will reclaim memory from any
object that no longer has a valid reference pointing to
it.
InventoryItem item1 = new InventoryItem ("Wrench", 20);
InventoryItem item2 = item1;
This sets item1 and item2 to point to the same object.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Garbage Collection
Address
An InventoryItem object
description:
units:
“Wrench”
20item1
Addressitem2
Here, both item1 and item2 point to the same
instance of the InventoryItem class.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Garbage Collection
null
An InventoryItem object
description:
units:
“Wrench”
20item1
Addressitem2
However, by running the command:
item1 = null;
only item2 will be pointing to the object.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Garbage Collection
null
An InventoryItem object
description:
units:
“Wrench”
20item1
nullitem2
If we now run the command:
item2 = null;
neither item1 or item2 will be pointing to the object.
Since there are no valid references to this
object, it is now available for the garbage
collector to reclaim.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Garbage Collection
null
An InventoryItem object
description:
units:
“Wrench”
20item1
nullitem2
The garbage collector reclaims
the memory the next time it runs
in the background.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The finalize Method
If a method with the signature:
public void finalize(){…}
is included in a class, it will run just prior to
the garbage collector reclaiming its memory.
The garbage collector is a background thread
that runs periodically.
It cannot be determined when the finalize
method will actually be run.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Class Collaboration
Collaboration – two classes interact with
each other
If an object is to collaborate with another
object, it must know something about the
second object’s methods and how to call
them
If we design a class StockPurchase that
collaborates with the Stock class
(previously defined), we define it to create
and manipulate a Stock object
See examples: StockPurchase.java, StockTrader.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
CRC Cards
Class, Responsibilities and Collaborations (CRC) cards
are useful for determining and documenting a class’s
responsibilities
The things a class is responsible for knowing
The actions a class is responsible for doing
CRC Card Layout (Example for the Stock class)
Stock
Know stock to purchase Stock class
Know number of shares None
Calculate cost of purchase Stock class
Etc. None or class name

More Related Content

What's hot (17)

Cso gaddis java_chapter6
Cso gaddis java_chapter6Cso gaddis java_chapter6
Cso gaddis java_chapter6
 
Generics
GenericsGenerics
Generics
 
Chap3java5th
Chap3java5thChap3java5th
Chap3java5th
 
Chap4java5th
Chap4java5thChap4java5th
Chap4java5th
 
Ap Power Point Chpt9
Ap Power Point Chpt9Ap Power Point Chpt9
Ap Power Point Chpt9
 
Collection framework
Collection frameworkCollection framework
Collection framework
 
Overview of Java
Overview of Java Overview of Java
Overview of Java
 
Ap Power Point Chpt5
Ap Power Point Chpt5Ap Power Point Chpt5
Ap Power Point Chpt5
 
Java -lec-6
Java -lec-6Java -lec-6
Java -lec-6
 
Lecture-05-DSA
Lecture-05-DSALecture-05-DSA
Lecture-05-DSA
 
Ap Power Point Chpt2
Ap Power Point Chpt2Ap Power Point Chpt2
Ap Power Point Chpt2
 
Creating classes and applications in java
Creating classes and applications in javaCreating classes and applications in java
Creating classes and applications in java
 
OOP Principles
OOP PrinciplesOOP Principles
OOP Principles
 
Chapter 4 Writing Classes
Chapter 4 Writing ClassesChapter 4 Writing Classes
Chapter 4 Writing Classes
 
Eo gaddis java_chapter_10_5e
Eo gaddis java_chapter_10_5eEo gaddis java_chapter_10_5e
Eo gaddis java_chapter_10_5e
 
String
StringString
String
 
L2 datatypes and variables
L2 datatypes and variablesL2 datatypes and variables
L2 datatypes and variables
 

Similar to Eo gaddis java_chapter_06_Classes and Objects

Cso gaddis java_chapter9ppt
Cso gaddis java_chapter9pptCso gaddis java_chapter9ppt
Cso gaddis java_chapter9pptmlrbrown
 
Eo gaddis java_chapter_03_5e
Eo gaddis java_chapter_03_5eEo gaddis java_chapter_03_5e
Eo gaddis java_chapter_03_5eGina Bullock
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...Sagar Verma
 
Dependency Injection in Spring
Dependency Injection in SpringDependency Injection in Spring
Dependency Injection in SpringASG
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfacesmadhavi patil
 
1 1 5 Clases
1 1 5 Clases1 1 5 Clases
1 1 5 ClasesUVM
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rdConnex
 
Eo gaddis java_chapter_07_5e
Eo gaddis java_chapter_07_5eEo gaddis java_chapter_07_5e
Eo gaddis java_chapter_07_5eGina Bullock
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelRamrao Desai
 
09slide.ppt oops classes and objects concept
09slide.ppt oops classes and objects concept09slide.ppt oops classes and objects concept
09slide.ppt oops classes and objects conceptkavitamittal18
 
‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3Mahmoud Alfarra
 
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5Anton Kasyanov
 

Similar to Eo gaddis java_chapter_06_Classes and Objects (20)

Cso gaddis java_chapter9ppt
Cso gaddis java_chapter9pptCso gaddis java_chapter9ppt
Cso gaddis java_chapter9ppt
 
Eo gaddis java_chapter_03_5e
Eo gaddis java_chapter_03_5eEo gaddis java_chapter_03_5e
Eo gaddis java_chapter_03_5e
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
 
Dependency Injection in Spring
Dependency Injection in SpringDependency Injection in Spring
Dependency Injection in Spring
 
Lecture 2 classes i
Lecture 2 classes iLecture 2 classes i
Lecture 2 classes i
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
1 1 5 Clases
1 1 5 Clases1 1 5 Clases
1 1 5 Clases
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
 
Classes2
Classes2Classes2
Classes2
 
Eo gaddis java_chapter_07_5e
Eo gaddis java_chapter_07_5eEo gaddis java_chapter_07_5e
Eo gaddis java_chapter_07_5e
 
slides 01.ppt
slides 01.pptslides 01.ppt
slides 01.ppt
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
 
Reflection
ReflectionReflection
Reflection
 
09slide.ppt
09slide.ppt09slide.ppt
09slide.ppt
 
09slide.ppt oops classes and objects concept
09slide.ppt oops classes and objects concept09slide.ppt oops classes and objects concept
09slide.ppt oops classes and objects concept
 
‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3
 
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5
 
Java basics
Java basicsJava basics
Java basics
 

More from Gina Bullock

Eo gaddis java_chapter_10_5e
Eo gaddis java_chapter_10_5eEo gaddis java_chapter_10_5e
Eo gaddis java_chapter_10_5eGina Bullock
 
Eo gaddis java_chapter_14_5e
Eo gaddis java_chapter_14_5eEo gaddis java_chapter_14_5e
Eo gaddis java_chapter_14_5eGina Bullock
 
Eo gaddis java_chapter_12_5e
Eo gaddis java_chapter_12_5eEo gaddis java_chapter_12_5e
Eo gaddis java_chapter_12_5eGina Bullock
 
Eo gaddis java_chapter_11_5e
Eo gaddis java_chapter_11_5eEo gaddis java_chapter_11_5e
Eo gaddis java_chapter_11_5eGina Bullock
 
Eo gaddis java_chapter_08_5e
Eo gaddis java_chapter_08_5eEo gaddis java_chapter_08_5e
Eo gaddis java_chapter_08_5eGina Bullock
 
Eo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eEo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eGina Bullock
 
Eo gaddis java_chapter_05_5e
Eo gaddis java_chapter_05_5eEo gaddis java_chapter_05_5e
Eo gaddis java_chapter_05_5eGina Bullock
 
Eo gaddis java_chapter_04_5e
Eo gaddis java_chapter_04_5eEo gaddis java_chapter_04_5e
Eo gaddis java_chapter_04_5eGina Bullock
 
Eo gaddis java_chapter_01_5e
Eo gaddis java_chapter_01_5eEo gaddis java_chapter_01_5e
Eo gaddis java_chapter_01_5eGina Bullock
 
Eo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eEo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eGina Bullock
 
Eo gaddis java_chapter_01_5e
Eo gaddis java_chapter_01_5eEo gaddis java_chapter_01_5e
Eo gaddis java_chapter_01_5eGina Bullock
 
Eo gaddis java_chapter_16_5e
Eo gaddis java_chapter_16_5eEo gaddis java_chapter_16_5e
Eo gaddis java_chapter_16_5eGina Bullock
 
Eo gaddis java_chapter_14_5e
Eo gaddis java_chapter_14_5eEo gaddis java_chapter_14_5e
Eo gaddis java_chapter_14_5eGina Bullock
 
Eo gaddis java_chapter_13_5e
Eo gaddis java_chapter_13_5eEo gaddis java_chapter_13_5e
Eo gaddis java_chapter_13_5eGina Bullock
 
Eo gaddis java_chapter_12_5e
Eo gaddis java_chapter_12_5eEo gaddis java_chapter_12_5e
Eo gaddis java_chapter_12_5eGina Bullock
 
Eo gaddis java_chapter_11_5e
Eo gaddis java_chapter_11_5eEo gaddis java_chapter_11_5e
Eo gaddis java_chapter_11_5eGina Bullock
 
Eo gaddis java_chapter_09_5e
Eo gaddis java_chapter_09_5eEo gaddis java_chapter_09_5e
Eo gaddis java_chapter_09_5eGina Bullock
 
Eo gaddis java_chapter_02_5e
Eo gaddis java_chapter_02_5eEo gaddis java_chapter_02_5e
Eo gaddis java_chapter_02_5eGina Bullock
 
Eo gaddis java_chapter_05_5e
Eo gaddis java_chapter_05_5eEo gaddis java_chapter_05_5e
Eo gaddis java_chapter_05_5eGina Bullock
 
Eo gaddis java_chapter_04_5e
Eo gaddis java_chapter_04_5eEo gaddis java_chapter_04_5e
Eo gaddis java_chapter_04_5eGina Bullock
 

More from Gina Bullock (20)

Eo gaddis java_chapter_10_5e
Eo gaddis java_chapter_10_5eEo gaddis java_chapter_10_5e
Eo gaddis java_chapter_10_5e
 
Eo gaddis java_chapter_14_5e
Eo gaddis java_chapter_14_5eEo gaddis java_chapter_14_5e
Eo gaddis java_chapter_14_5e
 
Eo gaddis java_chapter_12_5e
Eo gaddis java_chapter_12_5eEo gaddis java_chapter_12_5e
Eo gaddis java_chapter_12_5e
 
Eo gaddis java_chapter_11_5e
Eo gaddis java_chapter_11_5eEo gaddis java_chapter_11_5e
Eo gaddis java_chapter_11_5e
 
Eo gaddis java_chapter_08_5e
Eo gaddis java_chapter_08_5eEo gaddis java_chapter_08_5e
Eo gaddis java_chapter_08_5e
 
Eo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eEo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5e
 
Eo gaddis java_chapter_05_5e
Eo gaddis java_chapter_05_5eEo gaddis java_chapter_05_5e
Eo gaddis java_chapter_05_5e
 
Eo gaddis java_chapter_04_5e
Eo gaddis java_chapter_04_5eEo gaddis java_chapter_04_5e
Eo gaddis java_chapter_04_5e
 
Eo gaddis java_chapter_01_5e
Eo gaddis java_chapter_01_5eEo gaddis java_chapter_01_5e
Eo gaddis java_chapter_01_5e
 
Eo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eEo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5e
 
Eo gaddis java_chapter_01_5e
Eo gaddis java_chapter_01_5eEo gaddis java_chapter_01_5e
Eo gaddis java_chapter_01_5e
 
Eo gaddis java_chapter_16_5e
Eo gaddis java_chapter_16_5eEo gaddis java_chapter_16_5e
Eo gaddis java_chapter_16_5e
 
Eo gaddis java_chapter_14_5e
Eo gaddis java_chapter_14_5eEo gaddis java_chapter_14_5e
Eo gaddis java_chapter_14_5e
 
Eo gaddis java_chapter_13_5e
Eo gaddis java_chapter_13_5eEo gaddis java_chapter_13_5e
Eo gaddis java_chapter_13_5e
 
Eo gaddis java_chapter_12_5e
Eo gaddis java_chapter_12_5eEo gaddis java_chapter_12_5e
Eo gaddis java_chapter_12_5e
 
Eo gaddis java_chapter_11_5e
Eo gaddis java_chapter_11_5eEo gaddis java_chapter_11_5e
Eo gaddis java_chapter_11_5e
 
Eo gaddis java_chapter_09_5e
Eo gaddis java_chapter_09_5eEo gaddis java_chapter_09_5e
Eo gaddis java_chapter_09_5e
 
Eo gaddis java_chapter_02_5e
Eo gaddis java_chapter_02_5eEo gaddis java_chapter_02_5e
Eo gaddis java_chapter_02_5e
 
Eo gaddis java_chapter_05_5e
Eo gaddis java_chapter_05_5eEo gaddis java_chapter_05_5e
Eo gaddis java_chapter_05_5e
 
Eo gaddis java_chapter_04_5e
Eo gaddis java_chapter_04_5eEo gaddis java_chapter_04_5e
Eo gaddis java_chapter_04_5e
 

Recently uploaded

Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxhumanexperienceaaa
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
Analog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAnalog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAbhinavSharma374939
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 

Recently uploaded (20)

Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
Analog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAnalog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog Converter
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 

Eo gaddis java_chapter_06_Classes and Objects

  • 1. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C HA PT E R 6 A Second Lookat Classes and Objects
  • 2. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Topics Static Class Members Overloaded Methods Overloaded Constructors Passing Objects as Arguments to Methods Returning Objects from Methods The toString method Writing an equals method
  • 3. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Topics (cont’d) Methods that copy objects Aggregation The this Reference Variable Inner Classes Enumerated types Garbage Collection Object collaboration
  • 4. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Review of Instance Fields and Methods Each instance of a class has its own copy of instance variables. Example: The Rectangle class defines a length and a width field. Each instance of the Rectangle class can have different values stored in its length and width fields. Instance methods require that an instance of a class be created in order to be used. Instance methods typically interact with instance fields or calculate values based on those fields.
  • 5. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Static Class Members Static fields and static methods do not belong to a single instance of a class. To invoke a static method or use a static field, the class name, rather than the instance name, is used. Example: double val = Math.sqrt(25.0); Class name Static method
  • 6. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Static Fields Class fields are declared using the static keyword between the access specifier and the field type. private static int instanceCount = 0; The field is initialized to 0 only once, regardless of the number of times the class is instantiated. Primitive static fields are initialized to 0 if no initialization is performed. Examples: Countable.java, StaticDemo.java
  • 7. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Static Fields instanceCount field (static) 3 Object1 Object3Object2
  • 8. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Static Methods Methods can also be declared static by placing the static keyword between the access modifier and the return type of the method. public static double milesToKilometers(double miles) {…} When a class contains a static method, it is not necessary to create an instance of the class in order to use the method. double kilosPerMile = Metric.milesToKilometers(1.0); Examples: Metric.java, MetricDemo.java
  • 9. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Static Methods Static methods are convenient because they may be called at the class level. They are typically used to create utility classes, such as the Math class in the Java Standard Library. Static methods may not communicate with instance fields, only static fields.
  • 10. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Overloaded Methods Two or more methods in a class may have the same name; however, their parameter lists must be different. public class MyMath{ public static int square(int number){ return number * number; } public static double square(double number){ return number * number; } } Example: OverloadingDemo.java
  • 11. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Overloaded Methods Java uses the method signature (name, type of parameters and order of parameters) to determine which method to call. This process is known as binding. The return type of the method is not part of the method signature. Example: Pay.java, WeeklyPay.java
  • 12. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Overloaded Constructors Class constructors are also methods. This means that they can also be overloaded. Overloading constructors gives programmers more than one way to construct an object of that class. All of the previous restrictions on overloading apply to constructors as well. Example: Rectangle.java, TwoRectangles.java
  • 13. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Revisiting The Default Constructor Java automatically provides a default constructor for a class if a constructor is not explicitly written. The default constructor provided by Java: sets all numeric instance fields to 0 sets all char instance fields to ' ' (empty char) sets all reference instance fields to null sets all boolean instance fields to false
  • 14. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Revisiting The Default Constructor We, as programmers, can provide a no- arg constructor. This is a constructor that accepts no arguments. If a constructor that accepts arguments is written, we should also write a no- arg constructor. If we write a no-arg constructor, we should provide the initialization of all instance fields.
  • 15. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Revisiting The Default Constructor InventoryItem - description : String - units : int + InventoryItem() : + InventoryItem(d : String) : + InventoryItem(d : String, u : int) : + setDescription(d : String) : void + setUnits(u : int) : void + getDescription() : String + getUnits() : int
  • 16. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Passing Objects as Arguments Objects can be passed to methods as arguments. Java passes all arguments by value. When an object is passed as an argument, the value of the reference variable is passed. The value of the reference variable is an address or reference to the object in memory. A copy of the object is not passed, just a pointer to the object. When a method receives a reference variable as an argument, it is possible for the method to modify the contents of the object referenced by the variable. Example: Dealer.java, Player.java, ChoHan.java
  • 17. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Passing Objects as ArgumentsExamples: PassObject.java PassObject2.java displayRectangle(box); public static void displayRectangle(Rectangle r) { // Display the length and width. System.out.println("Length: " + r.getLength() + " Width: " + r.getWidth()); } A Rectangle object length: width: 12.0 5.0 Address
  • 18. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Returning References From Methods Methods are not limited to returning the primitive data types. Methods can return references to objects as well. Just as with passing parameters, a copy of the object is not returned, only its address. Example: ReturnObject.java Method return type: public static InventoryItem getData() { … return new InventoryItem(d, u); }
  • 19. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Returning Objects from Methodsitem = getData(); public static InventoryItem getData() { … return new InventoryItem(d, u); } description: units: Pliers address A InventoryItem Object 25
  • 20. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The toString Method The toString method of a class can be called explicitly: Stock xyzCompany = new Stock ("XYZ", 9.62); System.out.println(xyzCompany.toString()); However, the toString method does not have to be called explicitly but is called implicitly whenever you pass an object of the class to println or print. Stock xyzCompany = new Stock ("XYZ", 9.62); System.out.println(xyzCompany);
  • 21. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The toString method The toString method is also called implicitly whenever you concatenate an object of the class with a string. Stock xyzCompany = new Stock ("XYZ", 9.62); System.out.println("The stock data is:n" + xyzCompany);
  • 22. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The toString Method All objects have a toString method that returns the class name and a hash of the memory address of the object. We can override the default method with our own to print out more useful information. Examples: Stock.java, StockDemo1.java
  • 23. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The equals Method When the == operator is used with reference variables, the memory address of the objects are compared. The contents of the objects are not compared. All objects have an equals method. The default operation of the equals method is to compare memory addresses of the objects (just like the == operator).
  • 24. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The equals Method The Stock class has an equals method. If we try the following: Stock stock1 = new Stock("GMX", 55.3); Stock stock2 = new Stock("GMX", 55.3); if (stock1 == stock2) // This is a mistake! System.out.println("The objects are the same."); else System.out.println("The objects are not the same."); only the addresses of the objects are compared
  • 25. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The equals Method Compare objects by their contents rather than by their memory addresses. Instead of simply using the == operator to compare two Stock objects, we should use the equals method. public boolean equals(Stock object2) { boolean status; if(symbol.equals(Object2.symbol) && sharePrice == Object2.sharePrice) status = true; else status = false; return status; } See example: StockCompare.java
  • 26. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Methods That Copy Objects There are two ways to copy an object. You cannot use the assignment operator to copy reference types Reference only copy This is simply copying the address of an object into another reference variable. Deep copy (correct) This involves creating a new instance of the class and copying the values from one object into the new object. Example: ObjectCopy.java
  • 27. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Copy Constructors A copy constructor accepts an existing object of the same class and clones it. public Stock(Stock object 2) { symbol = object2.symbol; sharePrice = object2.sharePrice; } // Create a Stock object Stock company1 = new Stock("XYZ", 9.62); //Create company2, a copy of company1 Stock company2 = new Stock(company1);
  • 28. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Aggregation Creating an instance of one class as a reference in another class is called object aggregation. Aggregation creates a “has a” relationship between objects. Examples: Instructor.java, Textbook.java, Course.java, CourseDemo.java
  • 29. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Aggregation in UML Diagrams Course - courseName : String - Instructor : Instructor - textBook : TextBook + Course(name : String, instr : Instructor, text : TextBook) + getName() : String + getInstructor() : Instructor + getTextBook() : TextBook + toString() : String TextBook - title : String - author : String - publisher : String + TextBook(title : String, author : String, publisher : String) + TextBook(object2 : TextBook) + set(title : String, author : String, publisher : String) : void + toString() : String Instructor - lastName : String - firstName : String - officeNumber : String + Instructor(lname : String, fname : String, office : String) +Instructor(object2 : Instructor) +set(lname : String, fname : String, office : String): void + toString() : String
  • 30. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Returning References to Private Fields • Avoid returning references to private data elements. • Returning references to private variables will allow any object that receives the reference to modify the variable.
  • 31. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Null References A null reference is a reference variable that points to nothing. If a reference is null, then no operations can be performed on it. References can be tested to see if they point to null prior to being used. if(name != null) System.out.println("Name is: " + name.toUpperCase()); Examples: FullName.java, NameTester.java
  • 32. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The this Reference The this reference is simply a name that an object can use to refer to itself. The this reference can be used to overcome shadowing and allow a parameter to have the same name as an instance field. public void setFeet(int feet) { this.feet = feet; //sets the this instance’s feet field //equal to the parameter feet. } Local parameter variable Shadowed instance variable
  • 33. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The this Reference The this reference can be used to call a constructor from another constructor. public Stock(String sym) { this(sym, 0.0); } This constructor would allow an instance of the Stock class to be created using only the symbol name as a parameter. It calls the constructor that takes the symbol and the price, using sym as the symbol argument and 0 as the price argument. Elaborate constructor chaining can be created using this technique. If this is used in a constructor, it must be the first statement in the constructor.
  • 34. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Inner Classes Classes my have other classes nested within them. These inner classes have unique properties. An outer class can access the public members of an inner class. An inner class is not visible or accessible to code outside the outer class. An inner class can access the private members of the outer class.
  • 35. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Inner Classes Inner classes are defined inside the outer class. Compiled byte code for inner classes is stored in a separate file. The file’s name consists of: the name of the outer class followed by a $ character followed by the name of the inner class followed by .class RetailItem$CostData.class Example: RetailItem.java, InnerClassDemo.java
  • 36. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Enumerated Types Known as an enum Requires declaration and definition like a class Syntax: enum typeName { one or more enum constants } Definition: enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } – Declaration: Day WorkDay; // creates a Day enum Assignment: Day WorkDay = Day.WEDNESDAY;
  • 37. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Enumerated Types An enum is a specialized class Day.MONDAY Day.TUESDAY Day.WEDNESDAY Day.SUNDAY Day.THURSDAY Day.FRIDAY Day.SATURDAY address Each are objects of type Day, a specialized class Day workDay = Day.WEDNESDAY; The workDay variable holds the address of the Day.WEDNESDAY object
  • 38. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Enumerated Types - Methods toString – returns name of calling constant ordinal – returns the zero-based position of the constant in the enum. For example the ordinal for Day.THURSDAY is 4 equals – accepts an object as an argument and returns true if the argument is equal to the calling enum constant compareTo - accepts an object as an argument and returns a negative integer if the calling constant’s ordinal < than the argument’s ordinal, a positive integer if the calling constant’s ordinal > than the argument’s ordinal and zero if the calling constant’s ordinal == the argument’s ordinal. Examples: EnumDemo.java, CarType.java, SportsCar.java, SportsCarDemo.java
  • 39. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Enumerated Types - Switching Java allows you to test an enum constant with a switch statement. Example: SportsCarDemo2.java
  • 40. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Garbage Collection When objects are no longer needed they should be destroyed. This frees up the memory that they consumed. Java handles all of the memory operations for you. Simply set the reference to null and Java will reclaim the memory.
  • 41. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Garbage Collection The Java Virtual Machine has a process that runs in the background that reclaims memory from released objects. The garbage collector will reclaim memory from any object that no longer has a valid reference pointing to it. InventoryItem item1 = new InventoryItem ("Wrench", 20); InventoryItem item2 = item1; This sets item1 and item2 to point to the same object.
  • 42. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Garbage Collection Address An InventoryItem object description: units: “Wrench” 20item1 Addressitem2 Here, both item1 and item2 point to the same instance of the InventoryItem class.
  • 43. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Garbage Collection null An InventoryItem object description: units: “Wrench” 20item1 Addressitem2 However, by running the command: item1 = null; only item2 will be pointing to the object.
  • 44. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Garbage Collection null An InventoryItem object description: units: “Wrench” 20item1 nullitem2 If we now run the command: item2 = null; neither item1 or item2 will be pointing to the object. Since there are no valid references to this object, it is now available for the garbage collector to reclaim.
  • 45. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Garbage Collection null An InventoryItem object description: units: “Wrench” 20item1 nullitem2 The garbage collector reclaims the memory the next time it runs in the background.
  • 46. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The finalize Method If a method with the signature: public void finalize(){…} is included in a class, it will run just prior to the garbage collector reclaiming its memory. The garbage collector is a background thread that runs periodically. It cannot be determined when the finalize method will actually be run.
  • 47. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Class Collaboration Collaboration – two classes interact with each other If an object is to collaborate with another object, it must know something about the second object’s methods and how to call them If we design a class StockPurchase that collaborates with the Stock class (previously defined), we define it to create and manipulate a Stock object See examples: StockPurchase.java, StockTrader.java
  • 48. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CRC Cards Class, Responsibilities and Collaborations (CRC) cards are useful for determining and documenting a class’s responsibilities The things a class is responsible for knowing The actions a class is responsible for doing CRC Card Layout (Example for the Stock class) Stock Know stock to purchase Stock class Know number of shares None Calculate cost of purchase Stock class Etc. None or class name