Chap 8 Notes
Chap 8 Notes
A Second Look
at Classes and
Objects
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-2
Chapter Topics
Chapter 8 discusses the following main topics:
– Aggregation
– The this Reference Variable
– Enumerated Types
– Garbage Collection
– Focus on Object-Oriented Design: Class
Collaboration
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-3
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.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-4
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:
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-5
Static Fields
• Class fields are declared using the static keyword
between the access specifier and the field type.
private static int instanceCount = 0;
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-6
public class Countable
{
public static int instanceCount = 0;
public Countable()
{
instanceCount++;
}
public int getInstanceCount()
{
return instanceCount;
}
} public class StaticDemo
{ Output
public static void main(String[] args) 3 instances of the class were created.
{
int objectCount;
Countable object1 = new Countable();
Countable object2 = new Countable();
Countable object3 = new Countable();
objectCount = Countable.instanceCount;
System.out.println(objectCount + " instances of the class " + "were created.");
}
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-7
Static Fields
instanceCount field
(static)
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-8
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)
{…}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-9
public class Metric
{
public static double milesToKilometers(double m)
{
return m * 1.609;
}
public static double kilometersToMiles(double k)
{
return k / 1.609;
}
}
public class MetricDemo
{ Output
public static void main(String[] args) Enter a distance in miles:
{ 14
double miles, kilos; 14 miles equals 22.53 kilometers.
S.o.p (“Enter a distance in miles: ”) ; Enter a distance in kilometers:
miles = keyboard.nextDouble () ; 72
kilos = Metric.milesToKilometers(miles); 72 kilometers equals 44.75 miles.
S.o.p (“Enter a distance in kilometers:”) ;
kilos = keyboard.nextDouble () ;
miles = Metric.kilometersToMiles(kilos);
S.o.printf (“%.0f kilometers equals %.2f miles.\n”, kilos, miles) ;
}
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-10
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.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-11
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.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-12
Passing Objects as Arguments
Examples:
PassObject.java A Rectangle object
PassObject2.java length: 12.0
width: 5.0
displayRectangle(box);
Address
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-13
Returning Objects From Methods
• Methods are not limited to returning the primitive data
types.
• Methods can return references to objects as well.
• Just as with passing arguments, a copy of the object is not
returned, only its address.
• See example: ReturnObject.java
• Method return type:
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-14
Returning Objects from Methods
account = getAccount();
A BankAccount Object
balance: 3200.0
address
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-15
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());
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-16
The toString method
• The toString method is also called implicitly
whenever you concatenate an object of the class with a
string.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-17
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
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-18
public class Stock
{
private String symbol; // Trading symbol of stock
private double sharePrice; // Current price per share
public Stock(String sym, double price)
{
symbol = sym;
sharePrice = price;
}
public String getSymbol() { return symbol; }
public double getSharePrice() { return sharePrice; }
public String toString()
{
String str = "Trading symbol: " + symbol
+ "\nShare price: " + sharePrice;
return str;
} public class StockDemo1
} {
public static void main(String[] args)
{
Stock xyzCompany = new Stock ("XYZ", 9.62);
System.out.println(xyzCompany);
}
Output
}
Trading symbol: XYZ
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Share price: 9.62 7-19
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).
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-20
The equals Method
• The Stock class has an equals method.
• If we try the following:
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-21
The equals Method
• Instead of using the == operator to compare two Stock
objects, we should use the equals method.
public boolean equals(Stock object2)
{
boolean status;
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-22
public class Stock
{
private String symbol; // Trading symbol of stock
private double sharePrice; // Current price per share
public Stock(String sym, double price)
{ symbol = sym;
sharePrice = price;
}
// accessors & toString methods unchanged
public boolean equals(Stock object2)
{
if(symbol.equals(Object2.symbol && sharePrice ==
Object2.sharePrice)
return true ;
else return false ;
} public class StockDemo2
{
} public static void main(String[] args)
{
Stock company1 = new Stock ("XYZ", 9.62);
Stock company2 = new Stock ("XYZ", 9.62);
S.o.p (company1.equals (company2)
? “equal” : “not equal”) ; Output
} equal
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-23
Methods That Copy Objects
• There are two ways to copy an object.
– You cannot use the assignment operator to copy reference
types
– Example: ObjectCopy.java
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-24
public class Stock
{
private String symbol; // Trading symbol of stock
private double sharePrice; // Current price per share
public Stock(String sym, double price)
{ symbol = sym;
sharePrice = price;
}
// accessors & toString & equals methods unchanged
public Stock copy ()
{
return new Stock (symbol, sharePrice) ;
}
}
public class ObjectCopy
{
public static void main(String[] args)
{
Stock company1 = new Stock("XYZ", 9.62);
Stock company2;
company2 = company1.copy();
S.o.p (company2) ; Output
} Trading symbol: XYZ
} Share price: 9.62
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-25
Copy Constructors
• A copy constructor accepts an existing object of the same class
and clones it
public Stock(Stock object2)
{
symbol = object2.symbol;
sharePrice = object2.sharePrice;
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-26
public class Stock
{
private String symbol; // Trading symbol of stock
private double sharePrice; // Current price per share
public Stock(String sym, double price)
{ symbol = sym;
sharePrice = price;
}
public Stock(Stock object2) // copy constructor
{
symbol = object2.symbol;
sharePrice = object2.sharePrice;
}
// accessors & toString & equals & copy methods unchanged
}
public class ObjectCopy
{
public static void main(String[] args)
{
Stock company1 = new Stock("XYZ", 9.62);
Stock company2 = new Stock (company1);
S.o.p (company2) ;
} Output
} Trading symbol: XYZ
Share price: 9.62
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-27
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
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-28
Aggregation in UML Diagrams
Course
- courseName : String
- Instructor : Instructor
- textBook : TextBook
Instructor TextBook
- lastName : String - title : String
- firstName : String - author : String
- officeNumber : String - publisher : String
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-29
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.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-30
public class Instructor
{
private String lastName; // Last name
private String firstName; // First name
private String officeNumber; // Office number
public Instructor(String lname, String fname, String office)
{
lastName = lname;
firstName = fname;
officeNumber = office;
}
public Instructor(Instructor object2)
{
lastName = object2.lastName;
firstName = object2.firstName;
officeNumber = object2.officeNumber;
}
...
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-31
public class Instructor
{
...
public String toString()
{
return "Last Name: " + lastName + "\nFirst Name: "
+ firstName + "\nOffice Number: " + officeNumber;
}
public boolean equals (Instructor other)
{
return lastName.equals (other.lastName)
&& firstName.equals (other.firstName)
&& officeNumber.equals (other.officeNumber) ;
}
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-32
public class TextBook
{
private String title; // Title of the book
private String author; // Author's last name
private String publisher; // Name of publisher
public TextBook(String textTitle, String auth,
String pub)
{
title = textTitle;
author = auth;
publisher = pub;
}
public TextBook(TextBook object2)
{
title = object2.title;
author = object2.author;
publisher = object2.publisher;
}
...
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-33
public class TextBook
{
...
public String toString()
{
return "Title: " + title + "\nAuthor: " + author
+ "\nPublisher: " + publisher;
}
public boolean equals (TextBook other)
{
return other.title.equals (title)
&& author.equals (other.author)
&& other.publisher.equals (publisher) ;
}
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-34
public class Course
{
private String courseName; // Name of the course
private Instructor instructor; // The instructor
private TextBook textBook; // The textbook
public Course(String name, Instructor instr, TextBook text)
{
courseName = name;
instructor = new Instructor(instr);
textBook = new TextBook(text);
}
public Course (Course other) // copy constructor
{
courseName = other.courseName ;
instructor = other.getInstructor () ;
textBook = other.getTextBook () ;
}
...
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-35
public class Course
{
...
public String getName()
{
return courseName;
}
public Instructor getInstructor()
{
return new Instructor(instructor);
}
public TextBook getTextBook()
{
return new TextBook(textBook);
}
...
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-36
public class Course
{
...
public String toString()
{
String str = "Course name: " + courseName +
"\nInstructor Information:\n" +
instructor +
"\nTextbook Information:\n" +
textBook;
return str;
}
public boolean equals (Course other)
{
return other.courseName.equals (courseName)
&& instructor.equals (other.instructor)
&& other.textbook.equals (textBook) ;
}
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-37
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());
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-38
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.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-39
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.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-40
public class Stock
{
private String symbol; // Trading symbol of stock
private double sharePrice; // Current price per share
public Stock(String sym, double price)
{ symbol = sym;
sharePrice = price;
}
public Stock(Stock object2) // copy constructor with chaining
{
this (object2.symbol, object2.price) ;
}
public Stock () // no-arg constructor with chaining
{
this (“---”, 0.0) ;
}
// accessors & toString & equals & copy methods unchanged
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-41
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;
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-42
Enumerated Types
• An enum is a specialized class
Each are objects of type Day, a specialized class
Day.SUNDAY
address Day.WEDNESDAY
Day.THURSDAY
Day.FRIDAY
Day.SATURDAY
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-43
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
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-44
public class EnumDemo
{
enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY }
public static void main(String[] args)
{
Day workDay = Day.WEDNESDAY;
System.out.println(workDay);
System.out.println("The ordinal value for "
+ Day.SUNDAY + " is " + Day.SUNDAY.ordinal());
System.out.println("The ordinal value for "
+ Day.SATURDAY + " is " + Day.SATURDAY.ordinal());
if (Day.FRIDAY.compareTo(Day.MONDAY) > 0)
System.out.println(Day.FRIDAY + " is greater than "
+ Day.MONDAY);
else
System.out.println(Day.FRIDAY + " is NOT greater than "
+ Day.MONDAY);
}
} Output
WEDNESDAY
The ordinal value for SUNDAY is 0
The ordinal value for SATURDAY is 6
FRIDAY is greater than MONDAY
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-45
// SportsCar.java
public class SportsCar
{
private CarType make;
private CarColor color;
private double price;
public SportsCar(CarType aMake,
CarColor aColor, double aPrice)
{
make = aMake;
color = aColor;
price = aPrice;
}
...
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-46
// SportsCar.java
public class SportsCar
{
...
public CarType getMake()
{
return make;
}
public CarColor getColor()
{
return color;
}
public double getPrice()
{
return price;
}
public String toString()
{
String str = System.format ("Make: %s\n"
+ "Color: %s\nPrice: $%,.2f", make, color, price) ;
return str;
}
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-47
// CarType.java
enum CarType { PORSCHE, FERRARI, JAGUAR }
// SportsCarDemo.java
public class SportsCarDemo
{
public static void main(String[] args)
{
SportsCar yourNewCar = new SportsCar(CarType.PORSCHE,
CarColor.RED, 100000);
System.out.println(yourNewCar);
}
}
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-48
Enumerated Types - Switching
• Java allows you to test an enum constant with a
switch statement.
Example: SportsCarDemo2.java
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-49
// SportsCarDemo2.java
public class SportsCarDemo2
{
public static void main(String[] args)
{
SportsCar yourNewCar = new SportsCar(CarType.PORSCHE,
CarColor.RED, 100000);
switch (yourNewCar.getMake())
{
case PORSCHE :
System.out.println("Your car was made in Germany.");
break;
case FERRARI :
System.out.println("Your car was made in Italy.");
break;
case JAGUAR :
System.out.println("Your car was made in England.");
break;
default:
System.out.println("I'm not sure where that car "
+ "was made.");
}
}
} ©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7-50
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.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-51
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.
BankAccount account1 = new BankAccount(500.0);
BankAccount account2 = account1;
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-52
Garbage Collection
A BankAccount object
account2 Address
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-53
Garbage Collection
A BankAccount object
account2 Address
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-54
Garbage Collection
A BankAccount object
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-55
Garbage Collection
A BankAccount object
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-56
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.
• Note: finalize has been deprecated starting Java 9.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 8-57