1 / 54

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

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 {

hallam
Download Presentation

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

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. Code Listing 8-1 (Countable.java) 1 /** 2 This class demonstrates a static field. 3 */ 4 5 public class Countable 6 { 7 private staticint 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 */ 15 16 public Countable() 17 { 18 instanceCount++; 19 } 20 (Continued)

  3. 21 /** 22 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. 26 */ 27 28 public intgetInstanceCount() 29 { 30 return instanceCount; 31 } 32 }

  4. 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 // Create three instances 13Countable object1 = new Countable(); 14 Countable object2 = new Countable(); 15 Countable object3 = new Countable(); 16 17 18 19 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.

  5. 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. 10 @param m The distance in miles. 11 @return The distance in kilometers. 12 */ 13 14 public staticdouble milesToKilometers( double m ) 15 { 16 return m * 1.609; 17 } 18 (Continued)

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

  7. 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; 15 16 17 DecimalFormatfmt =new DecimalFormat("0.00"); 19 20 21 input = JOptionPane.showInputDialog("Enter" + "a distance in miles."); 23 miles = Double.parseDouble(input); (Continued)

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

  9. 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 voidmain(String[] args) 8 { 9 10 Rectangle box = new Rectangle(12.0, 5.0); 11 12 // Pass a reference to the object to // the displayRectangle method. 14 displayRectangle(box); // Where defined? 15 } 16 17 /** 18 The displayRectangle method displays the 19 length and width of a rectangle. 20 @param r A reference to a Rectangle 21 object. 22 */ (Continued)

  10. 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 } } Program Output Length : 12.0 Width : 5.0

  11. 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 { 10 11 Rectangle box = new Rectangle(12.0, 5.0); 12 13 14 System.out.println("Contents of the box object:"); 15 System.out.println("Length : " + box.getLength() + 16 " Width : " +box.getWidth()); 17 18 // Pass a reference to the object to the // changeRectangle method. 20 changeRectangle(box); (Continued)

  12. 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 } 28 29 /** 30 The changeRectangle method sets a Rectangle 31 object's length and width to 0. 32 @param r The Rectangle object to change. 33 */ 34 35 publicstaticvoid 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

  13. 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 voidmain(String[] args) 11 { 12 BankAccount account; 13 14 15 account = getAccount(); // Returns what? 16 17 18 JOptionPane.showMessageDialog(null, 19 "The account has a balance of $" + 20 account.getBalance()); 21 22 System.exit(0); 23 } (Continued)

  14. 24 25 /** 26 The getAccount method creates a BankAccount 27 object with the balance specified by the 28 user. 29 @return A reference to the object. 30 */ 31 32 public staticBankAccountgetAccount() 33 { 34 String input; // To hold input 35 double balance; // Account balance 36 37 38 input= JOptionPane.showInputDialog("Enter " + 39 "the account balance."); 40 balance = Double.parseDouble(input); 41 42 43 44 returnnewBankAccount(balance); 45 } 46 }

  15. 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 Stringsymbol; // Trading symbol of stock 8 private doublesharePrice; // Current price per share 9 10 /** 11 Constructor 12 @param sym The stock's trading symbol. 13 @param price The stock's share price. 14 */ 15 16 publicStock( String sym, double price ) 17 { 18 symbol = sym; 19 sharePrice = price; 20 } 21 (Continued)

  16. 22 /** 23 getSymbol method 24 @return The stock's trading symbol. 25 */ 26 27 public String getSymbol() 28 { 29 return symbol; 30 } 31 32 /** 33 getSharePrice method 34 @return The stock's share price 35 */ 36 37 public double getSharePrice() 38 { 39 return sharePrice; 40 } 41 (Continued)

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

  18. 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 voidmain(String[] args) 9 { 10 // Create a Stock object for the XYZ Company. 11 Stock xyzCompany = new Stock ("XYZ", 9.62); 14 // 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

  19. Code Listing 8-10 (StockCompare.java) 1 /** 2 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 7 { 8 public static voidmain(String[] args) 9 { 11 Stock company1 = new Stock("XYZ", 9.62); 12 Stock company2 = new Stock("XYZ", 9.62); 13 14 15 if (company1.equals(company2)) 16 System.out.println("Both objects are the same."); 17 else 18 System.out.println("The objects are different."); 19 } } Program Output Both objects are the same.

  20. Code Listing 8-11 (ObjectCopy.java) 1 /** 2 This program uses the Stock class's copy method 3 to create acopy of a Stock object. ( see pg. 517) 4 */ 5 6 public class ObjectCopy 7 { 8 public static void main(String[] args) 9 { 11 Stockcompany1 = new Stock("XYZ", 9.62); 12 14 Stock company2; 15 16 // copy()- makes a new stock object-uses IV’s of company1. // returns addr of new object company2 = company1.copy(); 19 20 // 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)

  21. 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.

  22. 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 10 11 /** 12 This constructor initializes the last name, 13 first name, and office number. 14 @param lname The instructor's last name. 15 @param fname The instructor's first name. 16 @param office The office number. 17 */ 18 19 publicInstructor(String lname, String fname, 20 String office) (Continued)

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

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

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

  26. 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 10 11 /** 12 This constructor initializes the title, 13 author, and publisher fields 14 @param textTitle The book's title. 15 @param auth The author's name. 16 @param pub The name of the publisher. 17 */ 18 19 public TextBook(String textTitle, String auth, 20 String pub) 21 { 22 title= textTitle; 23 author = auth; (Continued)

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

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

  29. 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 Instructorinstructor; // Course “has an” instructor 9 private TextBooktextBook; // Course “has a” textbook 10 11 /** 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 public Course(String name, Instructorinstr, 20 TextBooktext) 21 { 22 // Assign the courseName. 23 courseName = name; (Continued)

  30. 24 25 // Init IV with a “deep copy” of the parameter object. 26 27 instructor = new Instructor(instr); 28 29 // Init IV with a “deep copy” of the parameter object. 30 31 textBook =newTextBook(text); 32 } 33 34 /** 35 getName method 36 @return The name of the course. 37 */ 38 39 public String getName() 40 { 41 return courseName; 42 } 43 44 /** 45 getInstructor method 46 @return A reference to a copy of this course's (Continued)

  31. 47 Instructor object. 48 */ 49 50 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 527-529, “Shallow” copy and security 56 /** 57 getTextBook method 58 @return A reference to a copy of this course's 59 TextBook object. 60 */ 61 62 public TextBook getTextBook() 63 { 64 // Return a copy of the textBook object. 65 return new TextBook(textBook); // Same as comments above. 66 } 67 68 /** 69 toString method (Continued)

  32. 70 @return A string containing the course information. 71 */ 72 73 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 // “instructor” -Instructor class toString() //“textBook” - Textbook class toString() 83 return str; 84 } 85 }

  33. 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"); 12 13 // Create a TextBook object. 14 TextBook myTextBook = new TextBook("Starting Out with Java", 16 "Gaddis", "Addison-Wesley"); 17 18 // Create a Course object. 19 CoursemyCourse =new Course("Intro to Java", myInstructor,myTextBook); 22 23 // Display the course information. (Continued)

  34. 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

  35. 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 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)

  36. 24 The setFirstName method sets the firstName field. 25 @param str The String to set firstName to. 26 */ 27 28 public void setFirstName(String str) 29 { 30 firstName = str; 31 } 32 33 /** 34 The setMiddleName method sets the middleName field. 35 @param str The String to set middleName to. 36 */ 37 38 public void setMiddleName(String str) 39 { 40 middleName = str; 41 } 42 43 /** 44 The getLength method returns the length of the 45 full name. 46 @return The length. (Continued)

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

  38. 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 voidmain(String[] args) 11 { 12 int len; // To hold the name length 13 14 // Create a FullName object. 15 FullName name = new FullName(); 16 // Get the length of the full name. 18 len = name.getLength(); // Will cause crash! Why? 19 } 20 }

  39. 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 } 10 11 public static void main(String[] args) 12 { 13 14 Day workDay = Day.WEDNESDAY; 15 16 17 System.out.println(workDay); 18 20 21 System.out.println("The ordinal value for " + 22 Day.SUNDAY + " is " + 23 Day.SUNDAY.ordinal()); (Continued)

  40. 24 27 System.out.println("The ordinal value for " + 28 Day.SATURDAY + " is " + 29 Day.SATURDAY.ordinal()); 30 31 32 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

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

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

  43. 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 CarTypemake; // The car's make 10 private CarColor color; // The car's color 11 private double price; // The car's price 12 13 /** 14 The constructor initializes the car's make, 15 color, and price. 16 @param aMake The car's make. 17 @param aColor The car's color. 18 @param aPrice The car's price. 19 */ 20 21 public SportsCar( CarType aMake, CarColor aColor, 22 doubleaPrice) 23 { (Continued)

  44. 24 make = aMake; 25 color = aColor; 26 price = aPrice; 27 } 28 29 /** 30 getMake method 31 @return The car's make. 32 */ 33 34 public CarType getMake() 35 { 36 return make; 37 } 38 39 /** 40 getColor method 41 @return The car's color. 42 */ 43 44 publicCarColor getColor() 45 { 46 return color; (Continued)

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

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

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

  48. Code Listing 8-23 (SportsCarDemo2.java) 1 /** 2 This program shows that you can switchon an 3 enumerated type. 4 */ 5 6 public class SportsCarDemo2 7 { 8 public static void main(String[] args) 9 { 10 11 SportsCar yourNewCar = new SportsCar(CarType.PORSCHE, 12 CarColor.RED, 100000); 13 14 15 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 :

  49. 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 } } Program Output Your car was made in Germany.

  50. Code Listing 8-24 (StockPurchase.java) 1 /** The StockPurchase class represents a stock purchase. Class collaboration. Uses Stock class. 3 */ 4 5 public class StockPurchase 6 { 7 private Stockstock; // The stock that was purchased 8 private intshares; // Number of shares owned 9 10 /** 11 Constructor 12 @param stockObject The stock to purchase. 13 @param numShares The number of shares. 14 */ 15 16 publicStockPurchase(Stock stockObject, intnumShares) 17 { 18 // Create a copy of the object referenced by // stockObject. stock = newStock(stockObject); //CreatesStockobject copy. shares = numShares; 22 } 23 (Continued)

More Related