Starting Out with Java: From Control Structures through Objects 5 th edition By Tony Gaddis Source Code: Chapter 8.

Slides:



Advertisements
Similar presentations
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Advertisements

9-1 Chapter.8 Classes & Objects: A deeper look –Static Class Members –Passing & Returning Objects from Methods –The toString method –Writing an equals.
Chapter 8: A Second Look at Classes and Objects
More methods and classes, 4 of 4 Math 130 Introduction to Programming Lecture # 18 Monday, October 8, 2007.
© 2010 Pearson Addison-Wesley. All rights reserved. 9-1 Chapter Topics Chapter 9 discusses the following main topics: –Static Class Members –Passing Objects.
Chapter 6: A First Look at classes. Object-Oriented Programming  Object-oriented programming is centered on creating objects rather than procedures.
 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
Constants. 2 Objectives Describe ways to create constants –const –readonly –enum.
JOptionPane class. Dialog Boxes A dialog box is a small graphical window that displays a message to the user or requests input. A variety of dialog boxes.
Chapter 6: A First Look at Classes
Introduction to Classes and Objects (Through Ch 5) Dr. John P. Abraham Professor UTPA.
Class and Object. Class vs Object Let us consider the following scenario… Class defines a set of attributes/fields and a set of methods/services. Object.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
A Second Look at Classes and Objects. Contents A.Stock Purchase Problem B.Employee Problem C.Drawing Lines D.Exercises.
Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Starting Out with Java: From Control Structures through Objects
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
Lecture # 8 Constructors Overloading. Topics We will discuss the following main topics: – Static Class Members – Overloaded Methods – Overloaded Constructors.
9-2  Static Class Members  Passing Objects as Arguments to Methods  Returning Objects from Methods  The toString method  Writing an equals Method.
I NTRODUCTION TO PROGRAMMING Starting Out with Java: From Control Structures through Objects CS 146 Class Notes: Cooper & Ji & Varol Fall 09.
Chapter 8 A Second Look at Classes and Objects. SECTION 8.1 STATIC CLASS MEMBERS RoomAreas.java ( 課本 p. 372) Rectangle.java ( 課本 p. 366)
Chapter 3:Decision Structures.  3.1 The if Statement  3.2 The if-else Statement  3.3 The if-else-if Statement  3.4 Nested if Statements  3.5 Logical.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 11 Structured Data.
Introduction to Java Classes and Objects. What is a class A class is description of a structure that contains both data and methods – Describes a set.
A Second Look at Classes and Objects. Contents A.Stock Purchase Problem B.Employee Problem C.Drawing Lines D.Exercises.
Starting Out with Java: From Control Structures through Objects
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 11: Structured Data.
Chapter 4 Introduction to Classes, Objects, Methods and strings
Chapter 9: A Second Look at Classes and Objects
Chapter 9 – Part Tony Gaddis Modified by Elizabeth Adams.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
CONTENTS Wrapper Class Enumeration Garbage Collection Import static.
Page 4.1 – Autumn 2010Steffen Vissing Andersen SDJ I1, Autumn 2010 Agenda – Session 4 – 7. September 2009 Java fundamentals, checkpoint from chapter 2.
Ihsan Ayyub Qazi Introduction to Computer Programming Recitation 3 Ihsan Ayyub Qazi.
Starting Out with Java: From Control Structures through Objects 5 th edition By Tony Gaddis Source Code: Chapter 9.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 3 A First Look at Classes and Objects.
 2005 Pearson Education, Inc. All rights reserved. 1 Introduction to Classes and Objects.
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
A Second Look At Classes And Objects Chapter 9. Static Class Members When a value is stored in a static field, it is not in an object of the class. In.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 11: Structured Data.
1 Enums (Chapter 4) To enumerate is: to name things one after another in a list Java has a type, called an enum, where a programmer specifies a finite.
Starting Out with Java: From Control Structures through Objects 5 th edition By Tony Gaddis Source Code: Chapter 5.
Topics Instance variables, set and get methods Encapsulation
Class Everything in Java is in a class. The class has a constructor that creates the object. If you do not supply a constructor Java will create a default.
Starting Out With Java Control Structures to Objects By Tony Gaddis Copyright © 2005, Pearson Addison-Wesley. All rights reserved. Chapter 9 Slide #1 Review.
Powerpoint slides from A+ Computer Science Modified by Mr. Smith for his course.
Basic Class Structure. Class vs. Object class - a template for building an object –defines the instance data that the object will hold –defines instance.
Chapter 9 A Second Look at Classes and Objects - 4.
Chapter 9 A Second Look at Classes and Objects - 3 Aggregation.
Copyright © 2011 Pearson Education, Inc. Starting Out with Java: Early Objects Fourth Edition by Tony Gaddis Chapter 3: A First Look at Classes and Objects.
Chapter 9 A Second Look at Classes and Objects - 2.
3 Introduction to Classes and Objects.
Yanal Alahmad Java Workshop Yanal Alahmad
Topics Static Class Members Overloaded Methods Overloaded Constructors
A Second Look at Classes and Objects - 2
Chapter 9: A Second Look at Classes and Objects
Chapter 9: A Second Look at Classes and Objects
Java Programming with BlueJ
More on Classes and Objects
Today’s topics UML Diagramming review of terms
OBJECT ORIENTED PROGRAMMING II LECTURE 13_2 GEORGE KOUTSOGIANNAKIS
Lecture 5- Classes, Objects and Methods
CS-0401 INTERMEDIATE PROGRAMMING USING JAVA
Dr. Sampath Jayarathna Cal Poly Pomona
Starting Out with Java: From Control Structures through Objects
Chapter 6: A First Look at classes
Presentation transcript:

Starting Out with Java: From Control Structures through Objects 5 th edition By Tony Gaddis Source Code: Chapter 8

Code Listing 8-1 (Countable.java) 1 /** 2 This class demonstrates a static field. 3 */ 4 5 public class Countable 6 { 7 private static int instanceCount = 0; // What category of variable? 8 // What is it’s scope? 9 /** 10 The constructor increments the static 11 field instanceCount. This keeps track 12 of the number of instances of this 13 class that are created. 14 */ public Countable() 17 { 18 instanceCount ++; 19 } 20 (Continued)

21 /** 22 The getInstanceCount method returns 23 the number of instances of this class 24 that have been created. The value in the instanceCount field. 26 */ public int getInstanceCount() 29 { 30 return instanceCount; 31 } 32 }

Code Listing 8-2 (StaticDemo.java) 1 /** 2 This program demonstrates the Countable class. 3 */ 4 5 public class StaticDemo 6 { 7 public static void main (String[] args) 8 { 9 int objectCount; 10 11// Create three instances 13 Countable object1 = new Countable(); 14 Countable object2 = new Countable(); 15 Countable object3 = new Countable(); objectCount = object1.getInstanceCount(); 20 System.out.println(objectCount + 21 " instances of the class " + 22 "were created."); 23 } 24 } Program Output 3 instances of the class were created.

Code Listing 8-3 (Metric.java) 1 /** 2 This class demonstrates static methods. 3 */ 4 5 public class Metric 6 { 7 /** 8 The milesToKilometers method converts a 9 distance in miles to kilometers. m The distance in miles. The distance in kilometers. 12 */ public static double milesToKilometers( double m ) 15 { 16 return m * 1.609; 17 } 18 (Continued)

(Continued) Code Listing 8-3 (Metric.java) 19 /** 20 The kilometersToMiles method converts 21 a distance in kilometers to miles. k The distance in kilometers. The distance in miles. 24 */ public static double kilometersToMiles( double k ) 27 { 28 return k / 1.609; 29 } 30 }

Code Listing 8-4 (MetricDemo.java) 1 import javax.swing.JOptionPane; 2 import java.text.DecimalFormat; 3 4 /** 5 This program demonstrates the Metric class. 6 */ 7 8 public class MetricDemo 9 { 10 public static void main (String[] args) 11 { 12 String input; 13 double miles; 14 double kilos; DecimalFormat fmt = new DecimalFormat("0.00"); input = JOptionPane.showInputDialog (" Enter " + 22 " a distance in miles."); 23 miles = Double.parseDouble(input); (Continued)

26 kilos = Metric. milesToKilometers(miles); // Invoked thru? 27 JOptionPane.showMessageDialog(null, 28 fmt.format(miles) + " miles equals " + 29 fmt.format(kilos) + " kilometers."); input = JOptionPane.showInputDialog("Enter " + 33 " a distance in kilometers:"); 34 kilos = Double.parseDouble( input ); miles = Metric. kilometersToMiles (kilos); // Invoked thru? 38 JOptionPane.showMessageDialog(null, 39 fmt.format(kilos) + " kilometers equals " + 40 fmt.format(miles) + " miles."); System.exit(0); 43 } 44 }

Code Listing 8-5 (PassObject.java) 1 /** 2 This program passes an object as an argument. 3 */ 4 5 public class PassObject 6 { 7 public static void main (String[] args) 8 { 9 10 Rectangle box = new Rectangle(12.0, 5.0); // Pass a reference to the object to 13 // the displayRectangle method. 14 displayRectangle(box); // Where defined? 15 } /** 18 The displayRectangle method displays the 19 length and width of a rectangle. r A reference to a Rectangle 21 object. 22 */ (Continued)

23 24 public static void displayRectangle(Rectangle r ) 25 { 26 // Display the length and width. 27 System.out.println("Length : " + r.getLength() + // Calls an Instance Method 28 " Width : " + r.getWidth()); // from a static method 29 } 30} Program Output Length : 12.0 Width : 5.0

Code Listing 8-6 (PassObject2.java) 1 /** 2 This program passes an object as an argument. 3 The object is modified by the receiving method. 4 */ 5 6 public class PassObject2 7 { 8 public static void main (String[] args) 9 { Rectangle box = new Rectangle(12.0, 5.0); System.out.println(" Contents of the box object :"); 15 System.out.println("Length : " + box.getLength() + 16 " Width : " + box.getWidth()); // Pass a reference to the object to the 19 // changeRectangle method. 20 changeRectangle(box); (Continued)

23 System.out.println("\nNow the contents of the " + 24 " box object are:"); 25 System.out.println("Length : " + box.getLength() + 26 " Width : " + box. getWidth()); 27 } /** 30 The changeRectangle method sets a Rectangle 31 object's length and width to 0. r The Rectangle object to change. 33 */ public static void changeRectangle ( Rectangle r ) 36 { 37 r.setLength(0.0); 38 r.setWidth(0.0); 39 } 40 } Program Output Contents of the box object: Length : 12.0 Width : 5.0 Now the contents of the box object are: Length : 0.0 Width : 0.0

Code Listing 8-7 (ReturnObject.java) 1 import javax.swing.JOptionPane; 2 3 /** 4 This program demonstrates how a method 5 can return a reference to an object. 6 */ 7 8 public class ReturnObject 9 { 10 public static void main (String[] args) 11 { 12 BankAccount account; account = getAccount(); // Returns what? JOptionPane.showMessageDialog(null, 19 "The account has a balance of $" + 20 account.getBalance()); System.exit(0); 23 } (Continued)

24 25 /** 26 The getAccount method creates a BankAccount 27 object with the balance specified by the 28 user. A reference to the object. 30 */ public static BankAccount getAccount() 33 { 34 String input; // To hold input 35 double balance; // Account balance input = JOptionPane.showInputDialog(" Enter " + 39 "the account balance."); 40 balance = Double.parseDouble( input ); return new BankAccount(balance); 45 } 46 }

Code Listing 8-8 (Stock.java) 1 /** 2 The Stock class holds data about a stock. 3 */ 4 5 public class Stock 6 { 7 private String symbol; // Trading symbol of stock 8 private double sharePrice ; // Current price per share 9 10 /** 11 Constructor sym The stock's trading symbol. price The stock's share price. 14 */ public Stock ( String sym, double price ) 17 { 18 symbol = sym ; 19 sharePrice = price ; 20 } 21 (Continued)

22 /** 23 getSymbol method The stock's trading symbol. 25 */ public String getSymbol() 28 { 29 return symbol; 30 } /** 33 getSharePrice method The stock's share price 35 */ public double getSharePrice() 38 { 39 return sharePrice; 40 } 41 (Continued)

42 /** 43 toString method A string indicating the object's 45 trading symbol and share price. 46 */ public String toString() // EXPLICIT toString() 49 { 50 // Create a string describing the stock. 51 String str = "Trading symbol: " + symbol + 52 "\nShare price: " + sharePrice; return str; 56 } 57 }

Code Listing 8-9 (StockDemo1.java) 1 /** 2 This program demonstrates the Stock class's 3 toString method. 4 */ 5 6 public class StockDemo1 7 { 8 public static void main ( String[] args) 9 { 10 // Create a Stock object for the XYZ Company Stock xyzCompany = new Stock ("XYZ", 9.62); // Display the object's values. 16 System.out.println(xyzCompany) ; // What method is called? 17 } 18 } // Auto call under what 2 // conditions? Program Output Trading symbol: XYZ Share price: 9.62

Code Listing 8-10 (StockCompare.java) 1 /** 2 This program uses the Stock class's equals 3 method to compare two Stock objects. See for “equals”. 4 */ 5 6 public class StockCompare 7 { 8 public static void main ( String[] args) 9 { 11 Stock company1 = new Stock("XYZ", 9.62); 12 Stock company2 = new Stock("XYZ", 9.62); if (company1.equals(company2)) 16 System.out.println("Both objects are the same."); 17 else 18 System.out.println("The objects are different."); 19 } 20} Program Output Both objects are the same.

Code Listing 8-11 (ObjectCopy.java) 1 /** 2 This program uses the Stock class's copy method 3 to create a copy of a Stock object. ( see pg. 517) 4 */ 5 6 public class ObjectCopy 7 { 8 public static void main (String[] args) 9 { 11 Stock company1 = new Stock("XYZ", 9.62); Stock company2; // copy()- makes a new stock object-uses IV’s of company1. 17 // returns addr of new object 17 company2 = company1.copy(); // Display the contents of both objects. 21 System.out.println("Company 1:\n" + company1 ); // Calls toString() // implicitly 22 System.out.println(); 23 System.out.println("Company 2:\n" + company2 ); (Continued)

24 25 // Confirm that we actually have two objects. 26 if (company1 == company2) 27 { 28 System.out.println("The company1 and company2 " + 29 "variables reference the same object."); 30 } 31 else 32 { 33 System.out.println("The company1 and company2 " + 34 "variables reference different objects."); 35 } 36 } 37 } Program Output Company 1: Trading symbol: XYZ Share price: 9.62 Company 2: Trading symbol: XYZ Share price: 9.62 The company1 and company2 variables reference different objects.

Code Listing 8-12 (Instructor.java) 1 /** 2 This class stores data about an instructor. 3 */ 4 5 public class Instructor 6 { 7 private String lastName ; // Last name 8 private String firstName; // First name 9 private String officeNumber; // Office number /** 12This constructor initializes the last name, 13 first name, and office number. lname The instructor's last name. fname The instructor's first name. office The office number. 17 */ public Instructor (String lname, String fname, 20 String office) (Continued)

21 { 22 lastName = lname; 23 firstName = fname; 24 officeNumber = office; 25 } /** 28 The copy constructor initializes the object 29 as a copy of another Instructor object. object2 The object to copy. 31 */ public Instructor ( Instructor object2 ) 34 { 35 lastName = object2.lastName; 36 firstName = object2.firstName; 37 officeNumber = object2.officeNumber; 38 } /** 41 The set method sets a value for each field. lname The instructor's last name. (Continued)

fname The instructor's first name. office The office number. 45 */ public void set ( String lname, String fname, 48 String office) 49 { 50 lastName = lname; 51 firstName = fname; 52 officeNumber = office; 53 } /** 56 toString method A string containing the instructor 58 information. 59 */ 60 (Continued)

61 public String toString() 62 { 63 // Create a string representing the object. 64 String str = "Last Name: " + lastName + 65 "\nFirst Name: " + firstName + 66 "\nOffice Number: " + officeNumber; return str; 70 } 71 }

Code Listing 8-13 (TextBook.java) 1 /** 2 This class stores data about a textbook. 3 */ 4 5 public class TextBook 6 { 7 private String title; // Title of the book 8 private String author; // Author's last name 9 private String publisher; // Name of publisher /** 12 This constructor initializes the title, 13 author, and publisher fields textTitle The book's title. auth The author's name. pub The name of the publisher. 17 */ public TextBook (String textTitle, String auth, 20 String pub) 21 { 22 title = textTitle; 23 author = auth; (Continued)

24 publisher = pub; 25 } /** 28 The copy constructor initializes the object 29 as a copy of another TextBook object. object2 The object to copy. 31 */ public TextBook ( TextBook object2 ) 34 { 35 title = object2.title; 36 author = object2.author; 37 publisher = object2.publisher; 38 } /** 41 The set method sets a value for each field. textTitle The book's title. auth The author's name. pub The name of the publisher. 45 */ public void set (String textTitle, String auth, (Continued)

48 String pub) 49 { 50 title = textTitle; 51 author = auth; 52 publisher = pub; 53 } /** 56 toString method A string containing the textbook 58 information. 59 */ public String toString() 62 { 63 // Create a string representing the object. 64 String str = "Title: " + title + 65 "\nAuthor: " + author + 66 "\nPublisher: " + publisher; return str; 70 } 71 }

Code Listing 8-14 (Course.java) 1 /** 2 This class stores data about a course. Aggregate data. 3 */ 4 5 public class Course 6 { 7 private String courseName; // Name of the course 8 private Instructor instructor; // Course “has an” instructor 9 private TextBook textBook; // Course “has a” textbook /** 12 This constructor initializes the courseName, 13 instructor, and text fields. name The name of the course. instructor An Instructor object. text A TextBook object. 17 */ public Course ( String name, Instructor instr, 20 TextBook text ) 21 { 22 // Assign the courseName. 23 courseName = name; (Continued)

24 25 // Init IV with a “deep copy” of the parameter object instructor = new Instructor(instr); // Init IV with a “deep copy” of the parameter object textBook = new TextBook(text); 32 } /** 35 getName method The name of the course. 37 */ public String getName() 40 { 41 return courseName; 42 } /** 45 getInstructor method A reference to a copy of this course's (Continued)

47 Instructor object. 48 */ public Instructor getInstructor() 51 { 52 // Return a copy of the instructor object. 53 return new Instructor(instructor); // Returns a copy of object, not 54 } // reference to the object. 55 // See , “Shallow” copy and security 56 /** 57 getTextBook method A reference to a copy of this course's 59 TextBook object. 60 */ public TextBook getTextBook() 63 { 64 // Return a copy of the textBook object. 65 return new TextBook(textBook); // Same as comments above. 66 } /** 69 toString method (Continued)

A string containing the course information. 71 */ public String toString() 74 { 75 // Create a string representing the object. 76 String str = "Course name: " + courseName + 77 "\nInstructor Information:\n" + 78 instructor + 79 "\nTextbook Information:\n" + 80 textBook; 81 // “courseName” - String IV 82 // “instructor” - Instructor class toString() // “textBook” - Textbook class toString() 83 return str; 84 } 85 }

Code Listing 8-15 (CourseDemo.java) 1 /** 2 This program demonstrates the Course class. 3 */ 4 5 public class CourseDemo 6 { 7 public static void main (String[] args) 8 { 9 // Create an Instructor object. 10 Instructor myInstructor = new Instructor("Kramer", "Shawn", "RH3010"); // Create a TextBook object. 14 TextBook myTextBook = new TextBook("Starting Out with Java", 16 "Gaddis", "Addison-Wesley"); // Create a Course object. 19 Course myCourse = new Course("Intro to Java", myInstructor, myTextBook); // Display the course information. (Continued)

24 System.out.println(myCourse); // Implicit call to ? 25 } 26 Program Output Course name : Intro to Java Instructor Information: Last Name: Kramer First Name: Shawn Office Number: RH3010 Textbook Information: Title: Starting Out with Java Author: Gaddis Publisher: Addison-Wesley

Code Listing 8-16 (FullName.java) 1 /** 2 This class stores a person's first, last, and middle 3 names. The class is dangerous because it does not 4 prevent operations on null reference fields. 5 NOTE: No explicit constructor 5 */ 6 7 public class FullName 8 { 9 private String lastName; // Last name 10 private String firstName; // First name 11 private String middleName; // Middle name /** 14 The setLastName method sets the lastName field. str The String to set lastName to. 16 */ public void setLastName (String str) 19 { 20 lastName = str; 21 } /** (Continued)

24 The setFirstName method sets the firstName field. str The String to set firstName to. 26 */ public void setFirstName (String str) 29 { 30 firstName = str; 31 } /** 34 The setMiddleName method sets the middleName field. str The String to set middleName to. 36 */ public void setMiddleName (String str) 39 { 40 middleName = str; 41 } /** 44 The getLength method returns the length of the 45 full name. The length. (Continued)

47 */ public int getLength() 50 { 51 return lastName.length() + firstName.length() 52 + middleName.length(); 53 } /** 56 The toString method returns the full name. A reference to a String. 58 */ public String toString() 61 { 62 return firstName + " " + middleName + " " 63 + lastName; 64 } 65 }

Code Listing 8-17 (NameTester.java) 1 /** 2 This program creates a FullName object, and then 3 calls the object's getLength method before values 4 are established for its reference fields. As a 5 result, this program will crash. 6 */ 7 8 public class NameTester 9 { 10 public static void main (String[] args) 11 { 12 int len ; // To hold the name length // Create a FullName object. 15 FullName name = new FullName(); // Get the length of the full name. 18 len = name.getLength(); // Will cause crash! Why? 19 } 20 }

Code Listing 8-18 (EnumDemo.java) 1 /** 2 This program demonstrates an enumerated type. 3 */ 4 5 public class EnumDemo 6 { 7 8 enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, 9 THURSDAY, FRIDAY, SATURDAY } public static void main (String[] args) 12 { Day workDay = Day. WEDNESDAY; System.out.println(workDay); System.out.println(" The ordinal value for " + 22 Day.SUNDAY + " is " + 23 Day. SUNDAY. ordinal()); (Continued)

24 27 System.out.println ("The ordinal value for " + 28 Day.SATURDAY + " is " + 29 Day.SATURDAY.ordinal()); if ( Day.FRIDAY. compareTo (Day.MONDAY ) > 0 ) 33 System.out.println( Day. FRIDAY + " is greater than " + 34 Day. MONDAY ); 35 else 36 System.out.println( Day. FRIDAY + " is NOT greater than " + 37 Day. MONDAY ); 38 } 39 } Program Output WEDNESDAY The ordinal value for SUNDAY is 0 The ordinal value for SATURDAY is 6 FRIDAY is greater than MONDAY

Code Listing 8-19 (CarType.java) 1 /** 2 CarType enumerated data type 3 */ 4 5 enum CarType { PORSCHE, FERRARI, JAGUAR }

Code Listing 8-20 (CarColor.java) 1 /** 2 CarColor enumerated data type 3 */ 4 5 enum CarColor { RED, BLACK, BLUE, SILVER }

Code Listing 8-21 (SportsCar.java) 1 import java.text.DecimalFormat; 2 3 /** 4 SportsCar class 5 */ 6 7 public class SportsCar 8 { 9 private CarType make ; // The car's make 10 private CarColor color ; // The car's color 11 private double price ; // The car's price /** 14 The constructor initializes the car's make, 15 color, and price. aMake The car's make. aColor The car's color. aPrice The car's price. 19 */ public SportsCar ( CarType aMake, CarColor aColor, 22 double aPrice ) 23 { (Continued)

24 make = aMake; 25 color = aColor; 26 price = aPrice ; 27 } /** 30 getMake method The car's make. 32 */ public CarType getMake() 35 { 36 return make ; 37 } /** 40 getColor method The car's color. 42 */ public CarColor getColor() 45 { 46 return color; (Continued)

47 } /** 50 getPrice method The car's price. 52 */ public double getPrice() 55 { 56 return price; 57 } /** 60 toString method A string indicating the car's make, 62 color, and price. 63 */ public String toString() 66 { 67 // Create a DecimalFormat object for 68 // dollar formatting. 69 DecimalFormat dollar = new DecimalFormat("#,##0.00"); (Continued)

70 71 // Create a string representing the object. 72 String str = "Make: " + make + 73 "\nColor: " + color + 74 "\nPrice: $" + dollar.format(price); // Return the string. 77 return str; 78 } 79 }

Code Listing 8-22 (SportsCarDemo.java) 1 /** 2 This program demonstrates the SportsCar class. 3 */ 4 5 public class SportsCarDemo 6 { 7 public static void main( String[] args) 8 { 9 // Create a SportsCar object. 10 SportsCar yourNewCar = new SportsCar (CarType. PORSCHE, 11 CarColor. RED, ); System.out.println(yourNewCar); 15 } 16 } Program Output Make: PORSCHE Color: RED Price: $100,000.00

Code Listing 8-23 (SportsCarDemo2.java) 1 /** 2 This program shows that you can switch on an 3 enumerated type. 4 */ 5 6 public class SportsCarDemo2 7 { 8 public static void main( String[] args) 9 { SportsCar yourNewCar = new SportsCar(CarType.PORSCHE, 12 CarColor.RED, ); switch ( yourNewCar. getMake() ) 16 { 17 case PORSCHE : 18 System.out.println("Your car was made in Germany."); 19 break; 20 case FERRARI : 21 System.out.println("Your car was made in Italy."); 22 break; 23 case JAGUAR :

24 System.out.println("Your car was made in England."); 25 break; 26 default: 27 System.out.println("I'm not sure where that car " 28 + "was made."); 29 } 30 } 31} Program Output Your car was made in Germany.

Code Listing 8-24 (StockPurchase.java) 1 /** 2 The StockPurchase class represents a stock purchase. 3 Class collaboration. Uses Stock class. 3 */ 4 5 public class StockPurchase 6 { 7 private Stock stock; // The stock that was purchased 8 private int shares ; // Number of shares owned 9 10 /** 11 Constructor stockObject The stock to purchase. numShares The number of shares. 14 */ public StockPurchase ( Stock stockObject, int numShares ) 17 { 18 // Create a copy of the object referenced by 19 // stockObject. 20 stock = new Stock(stockObject) ; // Creates Stock object copy. 21 shares = numShares; 22 } 23 (Continued)

24 /** 25 getStock method A copy of the Stock object for the stock 27 being purchased. 28 */ public Stock getStock() 31 { 32 // Return a copy of the object referenced by stock. 33 return new Stock(stock); // Invoke Stock class copy constructor 34 } /** 37 getShares method The number of shares being purchased. 39 */ public int getShares() 42 { 43 return shares; 44 } /** (Continued)

47 getCost method The cost of the stock purchase. 49 */ public double getCost() 52 { 53 return shares * stock.getSharePrice(); // Invokes Stock method. 54 } 55 }

Code Listing 8-25 (StockTrader.java) 1 import java.util.Scanner; 2 3 /** 4 This program allows you to purchase shares of XYZ 5 company's stock. 6 */ 7 8 public class StockTrader 9 { 10 public static void main (String[] args) 11 { 12 int sharesToBuy ; // Number of shares to buy // Create a Stock object for the company stock. 16 // The trading symbol is XYZ and the stock is // currently $9.62 per share. 17 Stock xyzCompany = new Stock("XYZ", 9.62); Scanner keyboard = new Scanner(System.in); // Display the current share price. 23 System.out. printf ("XYZ stock is currently $%,.2f.\n", (Continued)

24 xyzCompany.getSharePrice()); // Get the number of shares to purchase. 27 System.out.print("How many shares do you want to buy? "); 28 sharesToBuy = keyboard.nextInt(); // Create a StockPurchase object for the transaction. 31 StockPurchase buy = 32 new StockPurchase(xyzCompany, sharesToBuy); // Display the cost of the transaction. 35 System.out.printf("Cost of the stock: $%,.2f", 36 buy.getCost()); 37 } 38 } Program Output with Example Input Shown in Bold XYZ stock is currently $9.62. How many shares do you want to buy? 100 [Enter] Cost of the stock: $962.00