Objects and Classes CHAPTER 4 In Chapter 2 we briefly introduced the concept of object-oriented programming. Students learned that objects are the primary building blocks of object-oriented software (as the name implies) and that a class is the blueprint from which an object is created. In Chapter 3 we examined some of the basic programming elements that make up an object and give it the ability to perform interesting tasks. It is in Chapter 4 that we explore how to define classes, create objects from classes, and use objects to solve problems. In our experience, the introduction to object-oriented programming should be gentle and natural. Although there may be a temptation to discuss procedural programming vs. object-oriented programming, this type of discussion is better suited for students that have solid applied knowledge of one technique or the other. Our approach for examples is intended to encourage thinking of objects. Applications are written with one class that has only a main method, with other classes and objects added for additional functionality. As mentioned in the discussion of Chapter 3, we avoid adding additional methods to the class containing the main method, because of it inherent procedural nature. There are three main examples in the chapter. The first is Tunes, in which the main method creates one object and passes messages to it. The second is Purchase_Power, which illustrates some of the true power in object-oriented programming. This example defines multiple objects that interact with each other and pass objects as parameters. Purchase_Power usually requires some significant exploration, but we’ve found that the benefits gained when students understand the techniques used in the program are worth the effort. The last example, Storm, is an applet that uses multiple objects to represent raindrops. The applet introduces a simple technique for animating a drawing without using event-driven programming. Exercises 4-9 Explain why encapsulation is an abstraction and give a specific example other than the ones presented in this chapter. Abstraction implies hiding details, the right details at the right time. Encapsulation is a form of abstraction because it hides the internal details of an object. For a client to make use of an object, the client only needs to access one of an object's service methods. The client does not need to know anything about how the service method, or any other aspect of object, actually works. An example of encapsulation is the telephone. If you want to talk to someone on the phone, you simply dial the phone and talk when someone answers. How the phones are connected is not necessary to understand. 4-10 Explain the difference between a method and a class. A method is part of a class. A method defines a single service that the class offers. A class is a collection of methods and variables and is used to create objects. 4-11 Write an expression that uses the Random class to produce a random number between: a) 0 and 1 b) 1 and 100 31 c) 10 and 100 d) -5 and 55 e) 3 and 4 f) -10000 and 10000 Not provided 4-12 Write a method called uppercase which accepts a lowercase alphabetic character and returns its uppercase equivalent. If the parameter is not a lowercase letter, return it unchanged. Instructor please note: This example is one that has a much better solution which involves casting (covered in Chapter 5), but at this point in the text we present this solution. Returning to this problem after covering casting has quite an impact on students. // ================================================================= // This method converts lower case letters into upper case letters. // If the character isn't a lower case letter, the character is not // changed. // ================================================================= public static char uppercase(char input_char) { char return_value = input_char; if (return_value == 'a') return_value = 'A'; else if (return_value == 'b') return_value = 'B'; else if (return_value == 'c') return_value = 'C'; else if (return_value == 'd') return_value = 'D'; else if (return_value == 'e') return_value = 'E'; else if (return_value == 'f') return_value = 'F'; else if (return_value == 'g') return_value = 'G'; else if (return_value == 'h') return_value = 'H'; else if (return_value == 'i') return_value = 'I'; else if (return_value == 'j') return_value = 'J'; else if (return_value == 'k') return_value = 'K'; else if (return_value == 'l') return_value = 'L'; else if (return_value == 'm') return_value = 'M'; 32 Chapter 4 Objects and Classes } else if (return_value == return_value = 'N'; else if (return_value == return_value = 'O'; else if (return_value == return_value = 'P'; else if (return_value == return_value = 'Q'; else if (return_value == return_value = 'R'; else if (return_value == return_value = 'S'; else if (return_value == return_value = 'T'; else if (return_value == return_value = 'U'; else if (return_value == return_value = 'V'; else if (return_value == return_value = 'W'; else if (return_value == return_value = 'X'; else if (return_value == return_value = 'Y'; else if (return_value == return_value = 'Z'; return return_value; // method uppercase 'n') 'o') 'p') 'q') 'r') 's') 't') 'u') 'v') 'w') 'x') 'y') 'z') 4-13 The value N! (pronounced N-factorial) is defined to be the product of the positive integers from 1 to N. Write a method to compute and return N!, where the value of N is passed in as a parameter. // ================================================== // This method returns the factorial of number. // ================================================== public double factorial(int number) { int count = 1; doubleresult = 1.0; while (count <= number) { result = result * count; count = count + 1; } return result; 33 } // method factorial 4-14 Think about representing an alarm clock as a software object. Then: a) list some characteristics of the object which represent its state and behavior The time of day The time the alarm is to go off Whether the alarm is set to go off or not Has a mechanism to set the time Has a mechanism to set the alarm time Has a mechanism to set the alarm The alarm rings at the set time b) define a class, as shown in Figure 4.8, to represent the object Alarm_Clock String time_of_day; String alarm_time; boolean alarm_switch; Alarm_Clock(); void set_time(String); void set_alarm(String); void turn_alarm_on(); void turn_alarm_off(); String print_time(); String print_alarm_time(); boolean alarm_on(); void ring_alarm(); 4-15 Repeat the steps in Problem 4-14, representing a basketball stadium scoreboard Not Provided 4-16 Repeat the steps in Problem 4-14, representing a daily schedule planner. 34 Chapter 4 Objects and Classes Not Provided 4-17 Repeat Problem 4-14, using an object you come up with yourself. Describe a program which might make use of the class you define. Not Provided Programming Projects 4-18 Write a class called Bank_Account that stores the current balance of the account and contains two methods to debit and credit the account. Define a third method which returns the current balance. Pass a value into a constructor to set an initial balance. Write a main method which instantiates two bank accounts and exercises the methods of the class. //******************************************************************* // // Accounts.java Programming Project Application // // Authors: Lewis and Loftus // // Classes: Accounts // Bank_Acount // //******************************************************************* //------------------------------------------------------------------// // Class Accounts contains the driver of a program that creates // and uses several bank account objects. // // Methods: // // public static void main (String[] args) // //------------------------------------------------------------------class Accounts { //=========================================================== // Creates and exercises two bank account objects. //=========================================================== public static void main (String[] args) { 35 Bank_Account Bank_Account joe = new Bank_Account (500.00); shiela = new Bank_Account (1000.00); System.out.println ("Joe's balance: " + joe.get_balance()); joe.credit (100.00); System.out.println ("Joe's balance: " + joe.get_balance()); joe.debit (75.00); System.out.println ("Joe's balance: " + joe.get_balance()); System.out.println(); System.out.println ("Shiela's shiela.get_balance()); shiela.credit (700.00); System.out.println ("Shiela's shiela.get_balance()); shiela.debit (2000.00); System.out.println ("Shiela's shiela.get_balance()); shiela.debit (1299.62); System.out.println ("Shiela's shiela.get_balance()); } } balance: " + balance: " + balance: " + balance: " + // method main // class Accounts //------------------------------------------------------------------// // Class Bank_Account // // Constructors: // // public Bank_Account (double initial_balance) // // Methods: // // public Bank_Account (double initial_balance) // public void credit (double amount) // public void debit (double amount) // public double get_balance () // //------------------------------------------------------------------class Bank_Account { 36 Chapter 4 Objects and Classes double current_balance; //=========================================================== // Sets up a bank account with the specified initial // balance. //=========================================================== public Bank_Account(double initial_balance) { current_balance = initial_balance; } // constructor Bank_Account //=========================================================== // Credits the account in question. //=========================================================== public void credit(double amount) { current_balance = current_balance + amount; System.out.println(amount + " credited."); } // method credit //=========================================================== // Debits the account in question. //=========================================================== public void debit(double amount) { if (current_balance >= amount) { current_balance = current_balance - amount; System.out.println(amount + " debited."); } else System.out.println("You cannot withdraw that much money."); } // method debit //=========================================================== // Returns the balance for the account in question. //=========================================================== public double get_balance() { return current_balance; } // method get_balance } // class Bank_Account 4-19 Write a class called Triangle that can be used to represent a triangle. It should include the following methods which return boolean values indicating if the particular property holds: 37 a) is_right (a right triangle) b) is_scalene (no two sides are the same length) c) is_isosceles (exactly two sides are the same length) d) is_equilateral (all three sides are the same length) //******************************************************************* // // Three_Sides.java Programming Project Application // // Authors: Lewis and Loftus // // Classes: Three_Sides // Triangle // //******************************************************************* //------------------------------------------------------------------// // Class Three_Sides // // Methods: // // public static void main (String[] args) // //------------------------------------------------------------------class Three_Sides { //=========================================================== // Create and determine properties of various triangles. //=========================================================== public static void main (String[] args) { Triangle Triangle Triangle Triangle right = new Triangle (3, 4, 5); equal = new Triangle (6, 6, 6); isosceles = new Triangle (3, 7, 7); scalene = new Triangle (4, 5, 6); // check the right triangle System.out.println(right.print_sides() + " triangle:"); if (right.is_right()) System.out.println("\tIt is a right triangle"); else 38 Chapter 4 Objects and Classes System.out.println("\tIt is not a right triangle"); if (right.is_isosceles()) System.out.println("\tIt is isosceles"); else System.out.println("\tIt is not isosceles"); if (right.is_equilateral()) System.out.println("\tIt is equilateral"); else System.out.println("\tIt is not a equilateral"); if (right.is_scalene()) System.out.println("\tIt is scalene"); else System.out.println("\tIt is not scalene"); System.out.println(); // check the equilateral triangle System.out.println(equal.print_sides() + " triangle:"); if (equal.is_right()) System.out.println("\tIt is a right triangle"); else System.out.println("\tIt is not a right triangle"); if (equal.is_isosceles()) System.out.println("\tIt is isosceles"); else System.out.println("\tIt is not isosceles"); if (equal.is_equilateral()) System.out.println("\tIt is equilateral"); else System.out.println("\tIt is not a equilateral"); if (equal.is_scalene()) System.out.println("\tIt is scalene"); else System.out.println("\tIt is not scalene"); System.out.println(); 39 // check the isosceles triangle System.out.println(isosceles.print_sides() + " triangle:"); if (isosceles.is_right()) System.out.println("\tIt is a right triangle"); else System.out.println("\tIt is not a right triangle"); if (isosceles.is_isosceles()) System.out.println("\tIt is isosceles"); else System.out.println("\tIt is not isosceles"); if (isosceles.is_equilateral()) System.out.println("\tIt is equilateral"); else System.out.println("\tIt is not equilateral"); if (isosceles.is_scalene()) System.out.println("\tIt is scalene"); else System.out.println("\tIt is not scalene"); System.out.println(); // check the scalene triangle System.out.println(scalene.print_sides() + " triangle:"); if (scalene.is_right()) System.out.println("\tIt is a right triangle"); else System.out.println("\tIt is not a right triangle"); if (scalene.is_isosceles()) System.out.println("\tIt is isosceles"); else System.out.println("\tIt is not isosceles"); if (scalene.is_equilateral()) System.out.println("\tIt is equilateral"); else System.out.println("\tIt is not equilateral"); if (scalene.is_scalene()) System.out.println("\tIt is scalene"); else 40 Chapter 4 Objects and Classes System.out.println("\tIt is not scalene"); } } // method main // class Three_Sides //------------------------------------------------------------------// // Class Triangle // // Constructors: // // public Triangle (int s1, int s2, int s3) { // // Methods: // // private int largest () // private int shortest () // public boolean is_right () // public boolean is_equilateral () // public boolean is_isosceles () // public boolean is_scalene () // //------------------------------------------------------------------class Triangle { int side1, side2, side3; //=========================================================== // Sets up a triangle with the specified side lengths. //=========================================================== public Triangle (int s1, int s2, int s3) { side1 = s1; side2 = s2; side3 = s3; } // constructor Triangle //=========================================================== // Returns the length of the longest side of the triangle. //=========================================================== private int largest () { int max = side1; 41 if (side2 > max) max = side2; if (side3 > max) max = side3; } return max; // method largest //=========================================================== // Returns the length of the shortest side of the triangle. //=========================================================== private int shortest () { int min = side1; if (side2 < min) min = side2; if (side3 < min) min = side3; } return min; // method shortest //=========================================================== // Determines whether the triangle is a right triangle. //=========================================================== public boolean is_right () { return ((side1 * side1 + side2 * side2) == (side3 * side3)); } //=========================================================== // Determines whether a triangle is equilateral. If the // longest side is equal to the shortest side, then the // triangle is equilateral. //=========================================================== public boolean is_equilateral () { int longest_side, shortest_side; longest_side = largest(); shortest_side = shortest(); } return (shortest_side == longest_side); // method is_equilateral //=========================================================== // Determines whether a triangle is isosceles. Any (and 42 Chapter 4 Objects and Classes // at least) two sides must be equal. //=========================================================== public boolean is_isosceles () { boolean answer; if (side1 == side2) answer = true; else if (side1 == side3) answer = true; else if (side2 == side3) answer = true; else answer = false; } return answer; // is_isosceles //=========================================================== // Determines whether a triangle is scalene. //=========================================================== public boolean is_scalene() { boolean answer; if (side1 == side2) answer = false; else if (side1 == side3) answer = false; else if (side2 == side3) answer = false; else answer = true; } return answer; // method is_scalene //=========================================================== // Prints the sides of the triangle. //=========================================================== public String print_sides() { return (side1 + " " + side2 + " " + side3); } // method print_sides 43 } // class Triangle 4-20 Write a class called String_Analyzer, which stores a string and provides several methods which determine and return the following characteristics. The string may contain several sentences. Each word in a sentence is separated by a single space character and each sentence is terminated with a period. One space separates each sentence. a) number of sentences in the string b) number of words in the entire string c) number of characters in the entire string d) average number of words per sentence e) average number of characters per word f) length of the longest word (in characters) g) length of the longest sentence (in words) Hint: use the charAt and lastIndexOf methods from the String class in the Java API. //******************************************************************* // // String_Evaluation.java Programming Project Application // // Authors: Lewis and Loftus // // Classes: String_Evaluation // String_Analyzer // //******************************************************************* //------------------------------------------------------------------// // Class String_Evaluation // // Methods: // // public static void main (String[] args) // //------------------------------------------------------------------class String_Evaluation { //=========================================================== 44 Chapter 4 Objects and Classes // Creteates a String_Analyzer object and exercises it. //=========================================================== public static void main (String[] args) { String_Analyzer dick = new String_Analyzer ("See Dick. See Jane. See Dick and Jane."); String_Analyzer spot = new String_Analyzer ("Take cognizance of Spot. Observe Spot progress expeditiously."); System.out.println("See Dick. See Jane. See Dick and Jane."); System.out.print("\tThe number of sentences in above string "); System.out.println("is: " + dick.num_sentences()); System.out.print("\tThe number of words in above string "); System.out.println("is: " + dick.num_words()); System.out.print("\tThe number of characters in above string "); System.out.println("is: " + dick.num_chars()); System.out.print("\tThe average number of words per sentence in "); System.out.println("above string is: " + dick.words_per_sent()); System.out.print("\tThe average number of characters per word in "); System.out.println("above string is: " + dick.chars_per_word()); System.out.println(); System.out.print("Take cognizance of Spot. "); System.out.println("Observe Spot progress expeditiously."); System.out.print("\tThe longest sentence in the above string is "); System.out.println(spot.longest_sent() + " words."); System.out.print("\tThe longest word in the above string is "); System.out.println(spot.longest_word() + " characters."); } } // method main // class String_Evalation //------------------------------------------------------------------// // Class String_Analyzer // // Constructors: // 45 // public String_Analyzer (String str) // // Methods: // // private boolean end_of_word (int pos) // public int num_sentences () // public int num_words () // public int num_chars () // public int words_per_sent () // public int chars_per_word () // public int longest_word () // public int longest_sent () // //------------------------------------------------------------------class String_Analyzer { final private char PERIOD = '.', SPACE = ' '; private String base_string; //=========================================================== // Sets up a new object with the specified string. //=========================================================== public String_Analyzer (String str) { base_string = str; } // constructor String_Analyzer //=========================================================== // Determines if the character at the specified position // is an end-of-word marker (period or space). //=========================================================== private boolean end_of_word (int pos) { boolean answer = false; if (pos != base_string.length()) { if (base_string.charAt(pos) == PERIOD) answer = true; else if (base_string.charAt(pos) == SPACE) answer = true; } return answer; } 46 // method end_of_word Chapter 4 Objects and Classes //=========================================================== // Determines the number of sentences in the base string. //=========================================================== public int num_sentences () { int position = 0, count = 0; while (position < base_string.length()){ if (base_string.charAt(position) == PERIOD) count = count + 1; position = position + 1; } return count; } // method num_sentences //=========================================================== // Determines the number of words in the base string. //=========================================================== public int num_words () { int position = 0; int count = 0; if (base_string.length() != 0) { while (position < base_string.length()){ if (base_string.charAt(position) == SPACE) count = count + 1; position = position + 1; } count = count + 1; } return count; } // method num_words //=========================================================== // Determines the number of characters in the base string. //=========================================================== public int num_chars () { return base_string.length(); } // method num_chars 47 //=========================================================== // Determines the average number of words per sentence. //=========================================================== public int words_per_sent () { return (num_words() / num_sentences()); } // method words_per_sent //=========================================================== // Determines the average number of characters per word. //=========================================================== public int chars_per_word() { return (num_chars() / num_words()); } // method chars_per_word //=========================================================== // Determines the length of the longest word, in chars. //=========================================================== public int longest_word () { int letter, max = 0, position = 0; while (position < base_string.length()) { letter = 0; // start of a new word while (end_of_word(position) == false) { letter = letter + 1; position = position + 1; } // move past period & leading space while (end_of_word(position)) position = position + 1; if (letter > max) max = letter; } return max; } // method longest_word //=========================================================== // Determines the length of the longest sentence, in words. //=========================================================== public int longest_sent () { 48 Chapter 4 Objects and Classes int word, max = 0, position = 0; while (position < base_string.length()) { word = 0; // start of a new sentence while (base_string.charAt(position) != PERIOD) { if (base_string.charAt(position) == SPACE) word = word + 1; position = position + 1; } word = word + 1; // count last word in sentence position = position + 2; // move past period & leading space if (word > max) max = word; } return max; } } // method longest_sent // class String_Analyzer 4-21 Write a class that uses the StringTokenizer class to identify the parts of a phone number. Assume that the format of the phone number is (nnn) nnn-nnnn. For example, given the phone number of (610) 555-1212, 610 is the areacode, 555 is the exchange, and 1212 is the extension. The class should have at least three public methods one that returns the areacode, one that returns the exchange, and one that returns the extension. Not Provided 49 50 Chapter 4 Objects and Classes