+ All Categories
Home > Documents > 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

Date post: 12-Jan-2016
Category:
Upload: hallam
View: 69 times
Download: 0 times
Share this document with a friend
Description:
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 { - PowerPoint PPT Presentation
Popular Tags:
54
Starting Out with Java: From Control Structures through Objects 5 th edition By Tony Gaddis Source Code: Chapter 8
Transcript
Page 1: Starting Out with Java: From Control Structures  through Objects 5 th  edition By Tony Gaddis

Starting Out with Java: From Control Structures

through Objects

5th edition

By Tony Gaddis

Source Code: Chapter 8

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

Code Listing 8-1 (Countable.java)1 /**

2 This class demonstrates a static field.3 */4

5 public class Countable6 {

7 private static int instanceCount = 0; // What category of variable?

8 // What is it’s scope?9 /**

10 The constructor increments the static11 field instanceCount. This keeps track12 of the number of instances of this13 class that are created.14 */15

16 public Countable()17 {

18 instanceCount++;19 }20

(Continued)

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

21 /**

22 The getInstanceCount method returns23 the number of instances of this class24 that have been created.25 @return The value in the instanceCount field.26 */27

28 public int getInstanceCount()29 {

30 return instanceCount;31 }32 }

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

Code Listing 8-2 (StaticDemo.java)1 /**

2 This program demonstrates the Countable class.3 */4

5 public class StaticDemo6 {

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();1617 18

19 objectCount = object1.getInstanceCount();20 System.out.println(objectCount +21 " instances of the class " +22 "were created.");23 }24 }

Program Output3 instances of the class were created.

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

Code Listing 8-3 (Metric.java)1 /**

2 This class demonstrates static methods.3 */4

5 public class Metric6 {7 /**8 The milesToKilometers method converts a9 distance in miles to kilometers.10 @param m The distance in miles.11 @return The distance in kilometers.12 */13

14 public static double milesToKilometers( double m )15 {

16 return m * 1.609;17 }18

(Continued)

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

(Continued) Code Listing 8-3 (Metric.java)19 /**20 The kilometersToMiles method converts21 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 }

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

Code Listing 8-4 (MetricDemo.java)1 import javax.swing.JOptionPane;2 import java.text.DecimalFormat;34 /**

5 This program demonstrates the Metric class.6 */7

8 public class MetricDemo9 {

10 public static void main(String[] args)

11 {

12 String input; 13 double miles; 14 double kilos; 1516

17 DecimalFormat fmt = new DecimalFormat("0.00");1920

21 input = JOptionPane.showInputDialog("Enter " +22 "a distance in miles.");

23 miles = Double.parseDouble(input);(Continued)

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

26 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);3536

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 }

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

Code Listing 8-5 (PassObject.java)1 /**

2 This program passes an object as an argument.3 */4

5 public class PassObject6 {

7 public static void main(String[] args)

8 {9

10 Rectangle box = new Rectangle(12.0, 5.0);11

12 // Pass a reference to the object to13 // the displayRectangle method.

14 displayRectangle(box); // Where defined?15 }1617 /**

18 The displayRectangle method displays the19 length and width of a rectangle.20 @param r A reference to a Rectangle21 object.22 */

(Continued)

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

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 method29 }

30 }

Program Output

Length : 12.0 Width : 5.0

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

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 PassObject27 {

8 public static void main(String[] args)

9 {10

11 Rectangle box = new Rectangle(12.0, 5.0);1213

14 System.out.println("Contents of the box object:");

15 System.out.println("Length : " + box.getLength() +

16 " Width : " + box.getWidth());1718 // Pass a reference to the object to the19 // changeRectangle method.

20 changeRectangle(box);

(Continued)

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

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 }2829 /**

30 The changeRectangle method sets a Rectangle31 object's length and width to 0.32 @param r The Rectangle object to change.33 */34

35 public static void changeRectangle( Rectangle r )36 {

37 r.setLength(0.0);

38 r.setWidth(0.0);39 }40 }

Program OutputContents of the box object:Length : 12.0 Width : 5.0Now the contents of the box object are:Length : 0.0 Width : 0.0

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

Code Listing 8-7 (ReturnObject.java)1 import javax.swing.JOptionPane;23 /**

4 This program demonstrates how a method5 can return a reference to an object.6 */7

8 public class ReturnObject9 {

10 public static void main(String[] args)

11 {

12 BankAccount account;1314

15 account = getAccount(); // Returns what?1617

18 JOptionPane.showMessageDialog(null,19 "The account has a balance of $" +

20 account.getBalance());21

22 System.exit(0);23 }

(Continued)

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

2425 /**

26 The getAccount method creates a BankAccount

27 object with the balance specified by the28 user.29 @return A reference to the object.30 */31

32 public static BankAccount getAccount()33 {

34 String input; // To hold input

35 double balance; // Account balance3637

38 input = JOptionPane.showInputDialog("Enter " +39 "the account balance.");

40 balance = Double.parseDouble(input);4142 43

44 return new BankAccount(balance); 45 }46 }

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

Code Listing 8-8 (Stock.java)1 /**

2 The Stock class holds data about a stock.3 */4

5 public class Stock6 {

7 private String symbol; // Trading symbol of stock

8 private double sharePrice; // Current price per share

910 /**

11 Constructor12 @param sym The stock's trading symbol.13 @param price The stock's share price.14 */15

16 public Stock( String sym, double price )

17 {

18 symbol = sym;

19 sharePrice = price;20 }21

(Continued)

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

22 /**23 getSymbol method24 @return The stock's trading symbol.25 */26

27 public String getSymbol()28 {

29 return symbol;30 }3132 /**33 getSharePrice method34 @return The stock's share price35 */36

37 public double getSharePrice()38 {

39 return sharePrice;40 }41

(Continued)

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

42 /**43 toString method44 @return A string indicating the object's45 trading symbol and share price.46 */47

48 public String toString() // EXPLICIT toString()49 {50 // Create a string describing the stock.

51 String str = "Trading symbol: " + symbol +52 "\nShare price: " + sharePrice;5354

55 return str;56 }57 }

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

Code Listing 8-9 (StockDemo1.java)1 /**

2 This program demonstrates the Stock class's3 toString method.4 */5

6 public class StockDemo17 {8 public static void main(String[] args)

9 {10 // Create a Stock object for the XYZ Company.11

12 Stock xyzCompany = new Stock ("XYZ", 9.62);14

15 // 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: XYZShare price: 9.62

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

Code Listing 8-10 (StockCompare.java)1 /**

2 This program uses the Stock class's equals3 method to compare two Stock objects. See 514-515 for “equals”.4 */5

6 public class StockCompare7 {

8 public static void main(String[] args)

9 {

11 Stock company1 = new Stock("XYZ", 9.62);12 Stock company2 = new Stock("XYZ", 9.62);1314

15 if (company1.equals(company2))16 System.out.println("Both objects are the same.");17 else18 System.out.println("The objects are different.");19 }

20 }

Program OutputBoth objects are the same.

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

Code Listing 8-11 (ObjectCopy.java)1 /**

2 This program uses the Stock class's copy method3 to create a copy of a Stock object. ( see pg. 517)4 */56 public class ObjectCopy7 {

8 public static void main(String[] args)9 {

11 Stock company1 = new Stock("XYZ", 9.62);12

14 Stock company2;15

16 // copy()- makes a new stock object-uses IV’s of company1.17 // returns addr of new object

17 company2 = company1.copy();1920 // Display the contents of both objects.

21 System.out.println("Company 1:\n" + company1); // Calls toString() // implicitly22 System.out.println();23 System.out.println("Company 2:\n" + company2);

(Continued)

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

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 else32 {33 System.out.println("The company1 and company2 " +34 "variables reference different objects.");35 }36 }37 }Program Output

Company 1:Trading symbol: XYZShare price: 9.62

Company 2:

Trading symbol: XYZShare price: 9.62The company1 and company2 variables reference different objects.

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

Code Listing 8-12 (Instructor.java)1 /**

2 This class stores data about an instructor.3 */4

5 public class Instructor6 {

7 private String lastName; // Last name

8 private String firstName; // First name

9 private String officeNumber; // Office number

1011 /**

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 public Instructor(String lname, String fname,

20 String office)

(Continued)

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

21 {22 lastName = lname;23 firstName = fname;24 officeNumber = office;25 }2627 /**

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 public Instructor( Instructor object2 )34 {

35 lastName = object2.lastName;36 firstName = object2.firstName;37 officeNumber = object2.officeNumber;38 }3940 /**

41 The set method sets a value for each field.

42 @param lname The instructor's last name.(Continued)

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

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 }5455 /**

56 toString method57 @return A string containing the instructor58 information.59 */60

(Continued)

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

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;6768

69 return str;70 }71 }

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

Code Listing 8-13 (TextBook.java)1 /**

2 This class stores data about a textbook.3 */4

5 public class TextBook6 {

7 private String title; // Title of the book

8 private String author; // Author's last name

9 private String publisher; // Name of publisher

1011 /**

12 This constructor initializes the title,

13 author, and publisher fields14 @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)

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

24 publisher = pub;25 }2627 /**

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 }3940 /**

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)

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

48 String pub)49 {50 title = textTitle;51 author = auth;52 publisher = pub;53 }5455 /**

56 toString method57 @return A string containing the textbook58 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;6768

69 return str;70 }71 }

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

Code Listing 8-14 (Course.java)1 /**

2 This class stores data about a course. Aggregate data.3 */4

5 public class Course6 {

7 private String courseName; // Name of the course

8 private Instructor instructor; // Course “has an” instructor

9 private TextBook textBook; // Course “has a” textbook1011 /**

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, Instructor instr,

20 TextBook text)21 {22 // Assign the courseName.23 courseName = name;

(Continued)

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

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 = new TextBook(text);32 }3334 /**

35 getName method36 @return The name of the course.37 */38

39 public String getName()40 {41 return courseName;42 }4344 /**

45 getInstructor method46 @return A reference to a copy of this course's

(Continued)

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

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, not54 } // reference to the object.55 // See 527-529, “Shallow” copy and security56 /**

57 getTextBook method58 @return A reference to a copy of this course's59 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 }6768 /**

69 toString method(Continued)

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

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

82 // “instructor” - Instructor class toString() // “textBook” - Textbook class toString()83 return str;84 }85 }

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

Code Listing 8-15 (CourseDemo.java)1 /**

2 This program demonstrates the Course class.3 */4

5 public class CourseDemo6 {

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 Course myCourse = new Course("Intro to Java", myInstructor, myTextBook);2223 // Display the course information.

(Continued)

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

24 System.out.println(myCourse); // Implicit call to ?25 }26

Program Output

Course name: Intro to Java

Instructor Information:Last Name: KramerFirst Name: ShawnOffice Number: RH3010

Textbook Information:Title: Starting Out with JavaAuthor: GaddisPublisher: Addison-Wesley

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

Code Listing 8-16 (FullName.java)1 /**

2 This class stores a person's first, last, and middle3 names. The class is dangerous because it does not4 prevent operations on null reference fields.5 NOTE: No explicit constructor5 */6

7 public class FullName8 {9 private String lastName; // Last name 10 private String firstName; // First name11 private String middleName; // Middle name1213 /**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 }2223 /**

(Continued)

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

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 }3233 /**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 }4243 /**44 The getLength method returns the length of the45 full name.46 @return The length.

(Continued)

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

47 */48

49 public int getLength()50 {

51 return lastName.length() + firstName.length()52 + middleName.length();53 }5455 /**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 }

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

Code Listing 8-17 (NameTester.java)1 /**

2 This program creates a FullName object, and then3 calls the object's getLength method before values4 are established for its reference fields. As a

5 result, this program will crash.6 */7

8 public class NameTester9 {

10 public static void main(String[] args)

11 {

12 int len; // To hold the name length

13

14 // Create a FullName object.15 FullName name = new FullName();16

17 // Get the length of the full name.

18 len = name.getLength(); // Will cause crash! Why?19 }20 }

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

Code Listing 8-18 (EnumDemo.java)1 /**

2 This program demonstrates an enumerated type.3 */4

5 public class EnumDemo6 {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;1516

17 System.out.println(workDay);1820

21 System.out.println("The ordinal value for " +

22 Day.SUNDAY + " is " +

23 Day.SUNDAY.ordinal());(Continued)

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

24

27 System.out.println("The ordinal value for " +

28 Day.SATURDAY + " is " +

29 Day.SATURDAY.ordinal());3031

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

WEDNESDAYThe ordinal value for SUNDAY is 0The ordinal value for SATURDAY is 6FRIDAY is greater than MONDAY

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

Code Listing 8-19 (CarType.java)

1 /**2 CarType enumerated data type3 */45 enum CarType { PORSCHE, FERRARI, JAGUAR }

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

Code Listing 8-20 (CarColor.java)

1 /**2 CarColor enumerated data type3 */45 enum CarColor { RED, BLACK, BLUE, SILVER }

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

Code Listing 8-21 (SportsCar.java)1 import java.text.DecimalFormat;23 /**4 SportsCar class5 */6

7 public class SportsCar8 {

9 private CarType make; // The car's make

10 private CarColor color; // The car's color

11 private double price; // The car's price1213 /**

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 double aPrice)23 {

(Continued)

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

24 make = aMake;25 color = aColor;26 price = aPrice;27 }2829 /**

30 getMake method31 @return The car's make.32 */33

34 public CarType getMake()35 {

36 return make;

37 }3839 /**40 getColor method41 @return The car's color.42 */43

44 public CarColor getColor()45 {

46 return color;(Continued)

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

47 }4849 /**

50 getPrice method51 @return The car's price.52 */53

54 public double getPrice()55 {

56 return price;57 }5859 /**

60 toString method61 @return A string indicating the car's make,62 color, and price.63 */64

65 public String toString()66 {67 // Create a DecimalFormat object for68 // dollar formatting.

69 DecimalFormat dollar = new DecimalFormat("#,##0.00");(Continued)

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

70

71 // Create a string representing the object.

72 String str = "Make: " + make +73 "\nColor: " + color +74 "\nPrice: $" + dollar.format(price);7576 // Return the string.

77 return str;78 }79 }

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

Code Listing 8-22 (SportsCarDemo.java)1 /**

2 This program demonstrates the SportsCar class.3 */4

5 public class SportsCarDemo6 {

7 public static void main(String[] args)

8 {

9 // 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: PORSCHEColor: REDPrice: $100,000.00

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

Code Listing 8-23 (SportsCarDemo2.java)1 /**

2 This program shows that you can switch on an3 enumerated type.4 */5

6 public class SportsCarDemo27 {

8 public static void main(String[] args)

9 {10

11 SportsCar yourNewCar = new SportsCar(CarType.PORSCHE,12 CarColor.RED, 100000);1314

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 :

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

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.

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

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 StockPurchase6 {

7 private Stock stock; // The stock that was purchased

8 private int shares; // Number of shares owned910 /**

11 Constructor12 @param stockObject The stock to purchase.13 @param numShares The number of shares.14 */15

16 public StockPurchase(Stock stockObject, int numShares)17 {

18 // Create a copy of the object referenced by19 // stockObject.

20 stock = new Stock(stockObject); // Creates Stock object copy.21 shares = numShares;22 }23

(Continued)

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

24 /**25 getStock method26 @return A copy of the Stock object for the stock27 being purchased.28 */29

30 public Stock getStock()31 {32 // Return a copy of the object referenced by stock.

33 return new Stock(stock); // Invoke Stock class copy constructor34 }3536 /**37 getShares method38 @return The number of shares being purchased.39 */40

41 public int getShares()42 {

43 return shares;44 }4546 /**

(Continued)

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

47 getCost method48 @return The cost of the stock purchase.49 */50

51 public double getCost()52 {

53 return shares * stock.getSharePrice(); // Invokes Stock method.54 }55 }

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

Code Listing 8-25 (StockTrader.java)1 import java.util.Scanner;23 /**

4 This program allows you to purchase shares of XYZ5 company's stock.6 */7

8 public class StockTrader9 {

10 public static void main(String[] args)

11 {

12 int sharesToBuy; // Number of shares to buy.13

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 Stock xyzCompany = new Stock("XYZ", 9.62);1820 Scanner keyboard = new Scanner(System.in);21

22 // Display the current share price.

23 System.out.printf("XYZ stock is currently $%,.2f.\n",

(Continued)

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

24 xyzCompany.getSharePrice());25

26 // Get the number of shares to purchase.

27 System.out.print("How many shares do you want to buy? ");

28 sharesToBuy = keyboard.nextInt();29

30 // Create a StockPurchase object for the transaction.

31 StockPurchase buy =

32 new StockPurchase(xyzCompany, sharesToBuy);33

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 BoldXYZ stock is currently $9.62.How many shares do you want to buy? 100 [Enter]Cost of the stock: $962.00


Recommended