Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Starting Out with Java: From Control Structures through Objects 5th edition By Tony Gaddis Source Code: Chapter 8 Code Listing 8-1 (Countable.java) 1 /** 2 3 4 This class demonstrates a static */ 5 6 public class Countable 7 field. { private static int instanceCount = 0; 8 9 /** 10 The constructor increments the static // What category of variable? // What is it’s scope? 11 field instanceCount. This keeps track 12 of the number of instances of this 13 class that are created. 14 */ 15 16 public 17 { Countable() 18 instanceCount++; 19 } 20 (Continued) 21 /** The getInstanceCount method returns 23 the number of instances of this class 24 that have been created. 25 @return The value in the instanceCount field. 22 26 */ 27 28 public 29 { int getInstanceCount() 30 return 31 } 32 } instanceCount; Code Listing 8-2 (StaticDemo.java) 1 2 3 4 /** 5 6 public class StaticDemo 7 8 public static void main(String[] args) { This program demonstrates the Countable class. */ { 9 10 int objectCount; 11 // Create three instances 13 Countable object1 = new Countable(); 14 Countable object2 = new Countable(); 15 Countable object3 = new Countable(); 16 17 18 19 20 21 22 23 } 24 } objectCount = object1.getInstanceCount(); System.out.println(objectCount + " instances of the class " + "were created."); Program Output 3 instances of the class were created. Code Listing 8-3 (Metric.java) 1 2 3 4 /** This class demonstrates static methods. */ 5 public class Metric 6 { 7 /** 8 The milesToKilometers method converts a 9 distance in miles to kilometers. 10 @param m The distance in miles. 11 @return The distance in kilometers. 12 */ 13 14 15 16 17 18 public static double milesToKilometers( double m ) { return m * 1.609; } (Continued) (Continued) Code Listing 8-3 (Metric.java) 19 20 21 22 23 24 25 /** 26 27 public static double kilometersToMiles( double k ) The kilometersToMiles method converts a distance in kilometers to miles. @param k The distance in kilometers. @return The distance in miles. */ { 28 29 } 30 } return k / 1.609; Code Listing 8-4 (MetricDemo.java) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 import javax.swing.JOptionPane; import java.text.DecimalFormat; /** This program demonstrates the Metric class. */ public class MetricDemo { public static void main(String[] args) { String input; double miles; double kilos; 17 19 20 DecimalFormat fmt = new DecimalFormat("0.00"); 21 22 input = JOptionPane.showInputDialog("Enter " + "a distance in miles."); 23 miles = Double.parseDouble(input); 26 27 28 29 30 32 33 34 35 36 kilos = Metric.milesToKilometers(miles); JOptionPane.showMessageDialog(null, fmt.format(miles) + " miles equals " + fmt.format(kilos) + " kilometers."); input = JOptionPane.showInputDialog("Enter " + "a distance in kilometers:"); kilos = Double.parseDouble(input); Metric.kilometersToMiles(kilos); 37 miles = 38 JOptionPane.showMessageDialog(null, 39 40 41 42 43 } 44 } // Invoked thru? fmt.format(kilos) + " kilometers equals " + fmt.format(miles) + " miles."); System.exit(0); // Invoked thru? Code Listing 8-5 (PassObject.java) 1 2 3 4 5 6 /** This program passes an object as an argument. */ public class PassObject { 7 public static void 8 9 { main(String[] args) Rectangle box = new Rectangle(12.0, 5.0); 10 11 12 13 // Pass a reference to the object to // the displayRectangle method. 14 displayRectangle(box); 15 16 17 18 19 20 21 22 // Where defined? } /** The displayRectangle method displays the length and width of a rectangle. @param r A reference to a Rectangle object. */ (Continued) 23 24 25 26 public static void displayRectangle(Rectangle r) { // Display the length and width. 27 System.out.println("Length : " + 28 29 " Width : " + } 30 } Program Output Length : 12.0 Width : 5.0 r.getLength() + // Calls an Instance Method r.getWidth()); // from a static method Code Listing 8-6 (PassObject2.java) 1 /** This program passes an object as an argument. The object is modified by the receiving method. 2 3 4 5 */ 6 7 public class PassObject2 8 9 10 { public { static void main(String[] args) 11 12 13 Rectangle box = new Rectangle(12.0, 5.0); 14 System.out.println("Contents of the box object:"); 15 System.out.println("Length : " + box.getLength() + " Width : " + box.getWidth()); 16 17 18 19 // Pass a reference to the object to the // changeRectangle method. 20 changeRectangle(box); (Continued) System.out.println("\nNow the contents of the " + "box object are:"); System.out.println("Length : " + box.getLength() + 23 24 25 26 27 28 29 30 31 32 33 34 35 36 " Width : " + box.getWidth()); } /** The changeRectangle method sets a Rectangle object's length and width to 0. @param r The Rectangle object to change. */ public static void changeRectangle( Rectangle r ) { 37 38 39 } 40 } r.setLength(0.0); r.setWidth(0.0); 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 2 3 4 5 import javax.swing.JOptionPane; /** This program demonstrates how a method can return a reference to an object. 6 7 */ 8 public class ReturnObject { 9 10 public static void 11 { main(String[] args) 12 13 14 BankAccount account; 15 16 17 18 account = getAccount(); JOptionPane.showMessageDialog(null, "The account has a balance of $" + 19 account.getBalance()); 20 21 System.exit(0); 22 23 } // Returns what? 24 25 26 27 28 29 30 31 32 33 34 /** The getAccount method creates a BankAccount object with the balance specified by the user. @return A reference to the object. */ public static BankAccount getAccount() { 35 36 37 38 39 40 41 42 43 44 45 } 46 } String input; double balance; // To hold input // Account balance input = JOptionPane.showInputDialog("Enter " + "the account balance."); balance = Double.parseDouble(input); return new BankAccount(balance); Code Listing 8-8 (Stock.java) 1 2 3 4 /** The Stock class holds data about a stock. */ 5 6 public class Stock 7 private String 8 9 10 11 12 13 14 15 private double 16 public Stock( String 17 { { // Trading symbol of stock // Current price per share /** Constructor @param sym The stock's trading symbol. @param price The stock's share price. */ sym, double price ) symbol = sym; sharePrice = price; 18 19 20 21 symbol; sharePrice; } (Continued) 22 23 24 25 26 /** 27 28 public String getSymbol() { 29 30 31 32 33 34 35 36 37 38 39 40 41 getSymbol method @return The stock's trading symbol. */ return symbol; } /** getSharePrice method @return The stock's share price */ public double getSharePrice() { return sharePrice; } (Continued) 42 43 44 45 46 47 /** toString method @return A string indicating the object's trading symbol and share price. */ public String toString() // { // Create a string describing the stock. 48 49 50 51 String str = "Trading symbol: " + symbol + "\nShare price: " + sharePrice; 52 53 54 return str; 55 56 57 EXPLICIT toString() } } Code Listing 8-9 (StockDemo1.java) 1 /** This program demonstrates the Stock class's 3 toString method. 2 4 5 6 7 8 9 10 11 */ public class StockDemo1 { public static void main(String[] args) { // Create a Stock object for the XYZ Company. 12 14 15 Stock xyzCompany = new Stock ("XYZ", 9.62); 16 17 18 System.out.println(xyzCompany); // Display the object's values. // What method is called? } } Program Output Trading symbol: XYZ Share price: 9.62 // Auto call under what 2 // conditions? Code Listing 8-10 (StockCompare.java) 1 2 3 /** This program uses the Stock class's equals method to compare two Stock objects. See 514-515 for “equals”. 4 5 */ 6 public class StockCompare { public static void main(String[] args) 7 8 9 { Stock company1 = new Stock("XYZ", 9.62); Stock company2 = new Stock("XYZ", 9.62); 11 12 13 14 if (company1.equals(company2)) System.out.println("Both objects are the same."); else System.out.println("The objects are different."); 15 16 17 18 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 to create a copy of a Stock object. ( see pg. 517) 3 4 5 6 7 8 9 11 12 14 15 16 17 */ public class ObjectCopy { public static void main(String[] args) { Stock company1 = new Stock("XYZ", 9.62); Stock company2; // copy()- makes a new stock object-uses IV’s of company1. // returns addr of new object 17 19 20 21 company2 = company1.copy(); 22 23 System.out.println(); System.out.println("Company 2:\n" + company2); // Display the contents of both objects. System.out.println("Company 1:\n" + company1); // Calls toString() // implicitly (Continued) 24 25 26 27 28 29 30 31 32 33 34 35 // Confirm that we actually have two objects. if (company1 == company2) { System.out.println("The company1 and company2 " + "variables reference the same object."); } else { System.out.println("The company1 and company2 " + "variables reference different objects."); } 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 3 4 5 6 /** This class stores data about an instructor. */ public class Instructor { 7 private String 8 private String 9 10 11 private String 12 13 14 15 16 17 18 19 20 lastName; firstName; officeNumber; // Last name // First name // Office number /** This constructor initializes the last name, first name, and office number. @param lname The instructor's last name. @param fname The instructor's first name. @param office The office number. */ public Instructor(String lname, String fname, String office) (Continued) 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 { lastName = lname; firstName = fname; officeNumber = office; } /** The copy constructor initializes the object as a copy of another Instructor object. @param object2 The object to copy. */ public { lastName = object2.lastName; firstName = object2.firstName; officeNumber = object2.officeNumber; 36 37 38 39 40 41 42 Instructor( Instructor object2 ) } /** The set method sets a value for each field. @param lname The instructor's last name. (Continued) 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 @param fname The instructor's first name. @param office The office number. */ public void set(String lname, String fname, String office) { lastName = lname; firstName = fname; officeNumber = office; } /** toString method @return A string containing the instructor information. */ (Continued) 61 62 public String toString() { 63 // Create a string representing the object. 64 65 66 67 68 String str = "Last Name: " + lastName + "\nFirst Name: " + firstName + "\nOffice Number: " + officeNumber; 69 70 } 71 } return str; Code Listing 8-13 (TextBook.java) 1 2 3 4 5 6 /** This class stores data about a textbook. */ public class TextBook { 7 private String 8 private String 9 10 11 private String 12 13 14 15 16 17 18 19 20 21 22 23 title; author; publisher; // Title of the book // Author's last name // Name of publisher /** This constructor initializes the title, author, and publisher fields @param textTitle The book's title. @param auth The author's name. @param pub The name of the publisher. */ public TextBook(String textTitle, String auth, String pub) { title = textTitle; author = auth; (Continued) 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 publisher = pub; } /** The copy constructor initializes the object as a copy of another TextBook object. @param object2 The object to copy. */ public TextBook( TextBook { title = object2.title; author = object2.author; publisher = object2.publisher; } object2 ) /** The set method sets a value for @param textTitle The book's title. @param auth The author's name. @param pub The name of the publisher. each field. */ public void set(String textTitle, String auth, (Continued) 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 String pub) { title = textTitle; author = auth; publisher = pub; } /** toString method @return A string containing the textbook information. */ public String toString() { // Create a string representing the object. String str = "Title: " + title + "\nAuthor: " + author + "\nPublisher: " + publisher; 69 70 } 71 } return str; Code Listing 8-14 (Course.java) 1 2 3 4 5 6 7 8 /** This class stores data about a course. Aggregate data. */ public class Course { courseName; private Instructor instructor; private TextBook textBook; private String 9 10 11 /** // Name of the course // Course “has an” instructor // Course “has a” textbook 12 This constructor initializes the courseName, 13 instructor, and text fields. 14 @param name The name of the course. 15 @param instructor An Instructor object. 16 @param text A TextBook object. 17 */ 18 19 20 21 22 23 public Course(String name, Instructor instr, TextBook text) { // Assign the courseName. courseName = name; (Continued) 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 // 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); } /** getName method @return The name of the course. */ public String getName() { return courseName; } /** getInstructor method @return A reference to a copy of this course's (Continued) 47 48 49 Instructor object. */ 50 51 52 53 54 55 56 57 58 59 60 61 public Instructor getInstructor() { // Return a copy of the instructor object. 62 63 64 65 66 67 68 69 public TextBook getTextBook() { // Return a copy of the textBook object. } return new Instructor(instructor); // Returns a copy of object, not // reference to the object. // See 527-529, “Shallow” copy and security /** getTextBook method @return A reference to a copy of this course's TextBook object. */ return new TextBook(textBook); // Same as comments above. } /** toString method (Continued) 70 71 72 @return A string containing the course information. */ 73 74 75 public String toString() { // Create a string representing the object. 76 77 78 79 80 String str = "Course name: " + courseName + "\nInstructor Information:\n" + instructor + "\nTextbook Information:\n" + textBook; // “courseName” - String IV // “instructor” - Instructor class toString() // “textBook” - Textbook class toString() 81 82 83 84 } 85 } return str; Code Listing 8-15 (CourseDemo.java) 1 2 3 4 5 6 7 8 9 10 12 13 14 16 17 18 19 22 23 /** This program demonstrates the Course class. */ public class CourseDemo { public static void { main(String[] args) // Create an Instructor object. Instructor myInstructor = new Instructor("Kramer", "Shawn", "RH3010"); // Create a TextBook object. TextBook myTextBook = new TextBook("Starting Out with Java", "Gaddis", "Addison-Wesley"); // Create a Course object. Course myCourse = new Course("Intro to Java", myInstructor, myTextBook); // Display the course information. (Continued) 24 25 26 System.out.println(myCourse); } 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 // Implicit call to ? Code Listing 8-16 (FullName.java) 1 2 3 4 5 /** This class stores a person's first, last, and middle names. The class is dangerous because it does not prevent operations on null reference fields. 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 12 13 /** 14 The setLastName method sets the lastName field. 15 @param str The String to set lastName to. 16 */ 17 18 public void setLastName(String str) 19 { 20 lastName = str; 21 } 22 23 /** (Continued) 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 The setFirstName method sets the firstName field. @param str The String to set firstName to. */ public void setFirstName(String str) { firstName = str; } /** The setMiddleName method sets the middleName field. @param str The String to set middleName to. */ public void setMiddleName(String str) { middleName = str; } /** The getLength method returns the length of the full name. @return The length. (Continued) 47 48 */ 49 50 51 public int getLength() { return lastName.length() + firstName.length() + middleName.length(); 52 53 54 55 56 57 58 59 } 60 61 62 public String toString() /** The toString method returns the full name. @return A reference to a String. */ { 63 64 } 65 } return firstName + " " + middleName + " " + lastName; Code Listing 8-17 (NameTester.java) 1 /** This program creates a FullName object, and then calls the object's getLength method before values are established for its reference fields. As a result, this program will crash. 2 3 4 5 6 7 8 9 10 11 */ public class NameTester { public static void main(String[] args) { 12 13 int len; 14 // Create a FullName object. FullName name = new FullName(); 15 16 // To hold the name length 17 // Get the length of the full name. 18 19 } 20 } len = name.getLength(); // Will cause crash! Why? Code Listing 8-18 (EnumDemo.java) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 /** This program demonstrates an enumerated type. */ public class EnumDemo { enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } public static void main(String[] args) { Day workDay = Day.WEDNESDAY; 15 16 17 18 20 System.out.println(workDay); 21 22 System.out.println("The ordinal value for " + 23 Day.SUNDAY + " is " + Day.SUNDAY.ordinal()); (Continued) 24 27 28 System.out.println("The ordinal value for " + Day.SATURDAY + " is " + Day.SATURDAY.ordinal()); 29 30 31 32 if (Day.FRIDAY.compareTo(Day.MONDAY ) > 0) System.out.println(Day.FRIDAY + " is greater than " + Day.MONDAY); 33 34 35 36 37 38 } else System.out.println(Day.FRIDAY + " is NOT greater than " + Day.MONDAY); 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) /** 2 CarType enumerated data type 3 */ 4 5 enum CarType { PORSCHE, FERRARI, JAGUAR } 1 Code Listing 8-20 (CarColor.java) /** 2 CarColor enumerated data type 3 */ 4 5 enum CarColor { RED, BLACK, BLUE, SILVER } 1 Code Listing 8-21 (SportsCar.java) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 import java.text.DecimalFormat; /** SportsCar class */ public class SportsCar { private CarType make; private CarColor color; private double price; // The car's make // The car's color // The car's price /** The constructor initializes the car's make, color, and price. @param aMake The car's make. @param aColor The car's color. @param aPrice The car's price. */ public SportsCar( CarType aMake, double aPrice) { CarColor aColor, (Continued) 24 25 26 make = aMake; color = aColor; price = aPrice; 27 28 29 30 31 32 33 } 34 35 public CarType { 36 37 38 39 40 41 42 43 44 45 46 /** getMake method @return The car's make. */ getMake() return make; } /** getColor method @return The car's color. */ public CarColor { getColor() return color; (Continued) 47 48 49 50 51 52 53 } 54 55 public double getPrice() { 56 57 58 59 60 61 62 63 64 return price; 65 66 67 68 69 /** getPrice method @return The car's price. */ } /** toString method @return A string indicating the car's make, color, and price. */ public String toString() { // Create a DecimalFormat object for // dollar formatting. DecimalFormat dollar = new DecimalFormat("#,##0.00"); (Continued) 70 71 72 73 74 75 76 77 78 } 79 } // Create a string representing the object. String str = "Make: " + make + "\nColor: " + color + "\nPrice: $" + dollar.format(price); // Return the string. return str; Code Listing 8-22 (SportsCarDemo.java) 1 2 3 4 5 6 7 8 9 10 /** This program demonstrates the SportsCar class. */ public class SportsCarDemo { public static void { main(String[] args) // Create a SportsCar object. . SportsCar yourNewCar = new SportsCar (CarType PORSCHE, 11 12 14 System.out.println(yourNewCar); 15 } 16 } Program Output Make: PORSCHE Color: RED Price: $100,000.00 . CarColor RED, 100000); Code Listing 8-23 (SportsCarDemo2.java) 1 2 3 /** This program shows that you can switch on an enumerated type. 4 5 */ 6 7 public class SportsCarDemo2 8 9 10 { public static void main(String[] args) { SportsCar yourNewCar = new SportsCar(CarType.PORSCHE, CarColor.RED, 100000); 11 12 13 14 . 15 switch ( yourNewCar getMake() ) 16 17 18 19 20 21 22 23 { 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."); 24 25 26 27 28 29 } 30 } 31 } Program Output Your car was made in Germany. Code Listing 8-24 (StockPurchase.java) 1 /** 2 3 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 The StockPurchase class represents a stock purchase. Class collaboration. Uses Stock class. */ public class StockPurchase { private Stock stock; private int // Number of shares owned /** Constructor @param stockObject The stock to purchase. @param numShares The number of shares. */ public StockPurchase(Stock { stockObject, int numShares) // Create a copy of the object referenced by // stockObject. 19 20 21 22 23 shares; // The stock that was purchased stock = new Stock(stockObject); shares = numShares; // Creates Stock object copy. } (Continued) 24 25 26 27 28 29 /** 30 31 32 public Stock getStock() { // Return a copy of the object referenced by stock. 33 34 35 36 37 38 39 40 41 42 43 44 45 46 getStock method @return A copy of the Stock object for the stock being purchased. */ return new Stock(stock); // Invoke Stock class copy constructor } /** getShares method @return The number of shares being purchased. */ public int getShares() { return shares; } /** (Continued) 47 48 49 50 51 52 getCost method @return The cost of the stock purchase. */ public double getCost() { 53 54 } 55 } return shares * stock.getSharePrice(); // Invokes Stock method. Code Listing 8-25 (StockTrader.java) 1 2 3 import java.util.Scanner; /** This program allows you to purchase shares of XYZ company's stock. 4 5 6 7 */ 8 9 public class StockTrader 10 11 12 13 { public static void main(String[] args) { int sharesToBuy; // Number of shares to buy. 14 // Create a Stock object for the company stock. 16 // The trading symbol is XYZ and the stock is // currently $9.62 per share. 17 18 20 21 22 Stock xyzCompany = new Stock("XYZ", 9.62); 23 System.out.printf("XYZ stock is currently $%,.2f.\n", Scanner keyboard = new Scanner(System.in); // Display the current share price. 24 25 xyzCompany.getSharePrice()); 26 27 28 29 // Get the number of shares to purchase. 30 // Create a StockPurchase object for the transaction. 31 StockPurchase buy = new StockPurchase(xyzCompany, sharesToBuy); 32 33 System.out.print("How many shares do you want to buy? "); sharesToBuy = keyboard.nextInt(); 34 // 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