Chapter 3 Using Classes and Objects Using Classes
Chapter 3 Using Classes and Objects
Using Classes and Objects • We can create more interesting programs using predefined classes and related objects • Chapter 3 focuses on: § § § § object creation and object references the String class and its methods the Java standard class library the Math classes formatting output enumerated types wrapper classes © 2004 Pearson Addison-Wesley. All rights reserved 2
Outline Creating Objects The Gregorian. Calendar Class The String Class Wrapper Classes Next Class: Packages Formatting Output Enumerated Types © 2004 Pearson Addison-Wesley. All rights reserved 3
Creating Objects • A variable holds either a primitive type or a reference to an object • A class name can be used as a type to declare an object reference variable String title; • No object is created with this declaration • An object reference variable holds the address of an object • The object itself must be created separately © 2004 Pearson Addison-Wesley. All rights reserved 4
Creating Objects • Generally, we use the new operator to create an object title = new String ("Java Software Solutions"); This calls the String constructor, which is a special method that sets up the object • Creating an object is called instantiation • An object is an instance of a particular class © 2004 Pearson Addison-Wesley. All rights reserved 5
Invoking Methods • We've seen that once an object has been instantiated, we can use the dot operator to invoke its methods count = title. length() • A method may return a value, which can be used in an assignment or expression • A method invocation can be thought of as asking an object to perform a service © 2004 Pearson Addison-Wesley. All rights reserved 6
References • Note that a primitive variable contains the value itself, but an object variable contains the address of the object • An object reference can be thought of as a pointer to the location of the object • Rather than dealing with arbitrary addresses, we often depict a reference graphically num 1 name 1 38 "Steve Jobs" 7
Assignment Revisited • The act of assignment takes a copy of a value and stores it in a variable • For primitive types: Before: num 1 38 num 2 96 num 2 = num 1; After: num 1 38 num 2 38 8
Reference Assignment • For object references, assignment copies the address: Before: name 1 "Steve Jobs" name 2 "Steve Wozniak" name 2 = name 1; After: name 1 "Steve Jobs" name 2 9
Aliases • Two or more references that refer to the same object are called aliases of each other • That creates an interesting situation: one object can be accessed using multiple reference variables • Aliases can be useful, but should be managed carefully • Changing an object through one reference changes it for all of its aliases, because there is really one object 10
Garbage Collection • When an object no longer has any valid references to it, it can no longer be accessed by the program • The object is useless, and therefore is called garbage • Java performs automatic garbage collection periodically, returning an object's memory to the system for future use • In other languages, the programmer is responsible for performing garbage collection 11
Outline Creating Objects The Gregorian. Calendar Class The String Class Wrapper Classes © 2004 Pearson Addison-Wesley. All rights reserved 12
Example of a Mutable Class • Gregorian. Calendar § Defined in java. util § Contains several constructors • Gregorian. Calendar() – Constructs a default Gregorian. Calendar using the current time in the default time zone with the default locale. • Gregorian. Calendar(int year, int month, int date) – Constructs a Gregorian. Calendar with the given date set in the default time zone with the default locale. • Gregorian. Calendar(int year, int month, int date, int hour, int minute) – Constructs a Gregorian. Calendar with the given date and time set for the default time zone with the default locale. © 2004 Pearson Addison-Wesley. All rights reserved 13
More on the Gregorian. Calendar • Contains 16 methods § boolean is. Leap. Year(int year) • Determines if the given year is a leap year. § void add(int field, int amount). • Inherits 31 method from the Calendar class § int get(int field) • What is a valid field? § Constants defined in Calendar class § Examples: YEAR, MONTH, DATE, DAY_OF_MONTH, DAY_OF_YEAR, DAY OF WEEK, WEEK_OF_YEAR, WEEK_OF_MONTH • Using the get method § int year = today. get(Calendar. YEAR); © 2004 Pearson Addison-Wesley. All rights reserved 14
Date Example // Demonstrates the Gregorian. Calendar, a mutable class import java. util. *; // for Gregorian. Calendar import java. text. *; // for Date. Format Class public class Date. Example { // Creates a Gregorian. Calendar object for the quiz. Day, outputs // information about the day, and modifies the day using class // methods public static void main(String [] args) { // Creates the quizday object to store the day of the quiz Gregorian. Calendar quiz. Day = new Gregorian. Calendar(2005, Calendar. OCTOBER, 1); int month, day; // store date attributes © 2004 Pearson Addison-Wesley. All rights reserved 15
Date Example // Get integer value for the characteristics day = quiz. Day. get(Calendar. DAY_OF_MONTH); System. out. println("Day: " + day); month = quiz. Day. get(Calendar. MONTH); System. out. println("Month: " + month); // Make the quiz 4 days earlier quiz. Day. add(Calendar. DAY_OF_MONTH, -4); // Get the new date day = quiz. Day. get(Calendar. DAY_OF_MONTH); System. out. println("Day 50 days after the quiz: " + day); month = quiz. Day. get(Calendar. MONTH); System. out. println("Month 50 days after the quiz: " + month ); // Format the output of the date using Date. Format fmt = Date. Format. get. Instance(); System. out. println("Formatted Date: " + fmt. format(quiz. Day. get. Time())); } } © 2004 Pearson Addison-Wesley. All rights reserved 16
Primitive Types vs. Objects with Assignment Statements int x = 5; int y = x; x++; Gregorian. Calendar d 1 = new Gregorian. Calendar(2005, Caldendar. October, 1); Gregorian. Calendar d 2 = d 1; d 1. add(Calendar. YEAR, 5); © 2004 Pearson Addison-Wesley. All rights reserved 17
Fix using clone method Gregorian. Calendar d 1 = new Gregorian. Calendar(2005, Caldendar. October, 1); Gregorian. Calendar d 2 = (Gregorian. Calendar) d 1. clone(); d 1. add(Calendar. YEAR, 5); © 2004 Pearson Addison-Wesley. All rights reserved 18
Outline Creating Objects The Gregorian. Calendar Class The String Class Wrapper Classes © 2004 Pearson Addison-Wesley. All rights reserved 19
The String Class • Because strings are so common, we don't have to use the new operator to create a String object title = "Java Software Solutions"; • This is special syntax that works only for strings • Each string literal (enclosed in double quotes) represents a String object © 2004 Pearson Addison-Wesley. All rights reserved 20
String Methods • Once a String object has been created, neither its value nor its length can be changed • Thus we say that an object of the String class is immutable • However, several methods of the String class return new String objects that are modified versions of the original • See the list of String methods on page 119 and in Appendix M or the Java online documentation: http: //java. sun. com/j 2 se/1. 5. 0/docs/api/index. html © 2004 Pearson Addison-Wesley. All rights reserved 21
String Indexes • It is occasionally helpful to refer to a particular character within a string • This can be done by specifying the character's numeric index • The indexes begin at zero in each string • In the string "Hello", the character 'H' is at index 0 and the 'o' is at index 4 © 2004 Pearson Addison-Wesley. All rights reserved 22
//******************************* // String. Mutation. java Author: Lewis/Loftus // // Demonstrates the use of the String class and its methods. //******************************* public class String. Mutation { //----------------------------- // Prints a string and various mutations of it. //----------------------------- public static void main (String[] args) { String phrase = "Change is inevitable"; String mutation 1, mutation 2, mutation 3, mutation 4; System. out. println ("Original string: "" + phrase + """); System. out. println ("Length of string: " + phrase. length()); mutation 1 = phrase. concat(", except from vending machines. "); mutation 2 = mutation 1. to. Upper. Case(); mutation 3 = mutation 2. replace ('E', 'X'); mutation 4 = mutation 3. substring (3, 30); © 2004 Pearson Addison-Wesley. All rights reserved 23
// Print each mutated string System. out. println ("Mutation #1: " + mutation 1); System. out. println ("Mutation #2: " + mutation 2); System. out. println ("Mutation #3: " + mutation 3); System. out. println ("Mutation #4: " + mutation 4); System. out. println ("Mutated length: " + mutation 4. length()); } } Output: Original string: "Change is inevitable" Length of string: 20 Mutation #1: Change is inevitable, except from vending machines. Mutation #2: CHANGE IS INEVITABLE, EXCEPT FROM VENDING MACHINES. Mutation #3: CHANGX IS INXVITABLX, XXCXPT FROM VXNDING MACHINXS. Mutation #4: NGX IS INXVITABLX, XXCXPT F Mutated length: 27 © 2004 Pearson Addison-Wesley. All rights reserved 24
String Methods (We are interested in) • str. length() – returns int • str. char. At(int) – returns char • str. substring(int) or str. substring(int, int) – returns String • str. index. Of(String) or str. index. Of(String, int) – returns int • • § str. last. Index. Of(String)or str. last. Index. Of(String, int) – returns int str. to. Upper. Case() – returns String str. to. Lower. Case() – returns String str. trim() – returns String © 2004 Pearson Addison-Wesley. All rights reserved 25
Storing and Displaying Method Results String saying = “All roads lead to Rome”; • Use assignment statements to store the result of a method call § int pos. Blank = saying. index. Of(“ “); • § String first. Word = saying. index. Of(0, pos. Blank); • • Including the method call in the output statement § System. out. println (“The second blank is at position “ + saying. index. Of(“ “, 4)); © 2004 Pearson Addison-Wesley. All rights reserved 26
Tricks of the trade • Use the results of one method as the input to another char last = str. char. At(str. length()-1); • Concatenating methods together int end. First. Word = str. trim(). index. Of(“ “); © 2004 Pearson Addison-Wesley. All rights reserved 27
Outline Creating Objects The Gregorian. Calendar Class The String Class Wrapper Classes © 2004 Pearson Addison-Wesley. All rights reserved 28
Wrapper Classes • The java. lang package contains wrapper classes that correspond to each primitive type: Primitive Type Wrapper Class byte Byte short Short int Integer long Long float Float double Double char Character boolean Boolean void Void © 2004 Pearson Addison-Wesley. All rights reserved 29
Wrapper Classes • The following declaration creates an Integer object which represents the integer 40 as an object Integer age = new Integer(40); • An object of a wrapper class can be used in any situation where a primitive value will not suffice • For example, some objects serve as containers of other objects • Primitive values could not be stored in such containers, but wrapper objects could be © 2004 Pearson Addison-Wesley. All rights reserved 30
Wrapper Classes • Wrapper classes also contain static methods that help manage the associated type • For example, the Integer class contains a method to convert an integer stored in a String to an int value: num = Integer. parse. Int(str); • The wrapper classes often contain useful constants as well • For example, the Integer class contains MIN_VALUE and MAX_VALUE which hold the smallest and largest int values © 2004 Pearson Addison-Wesley. All rights reserved 31
Autoboxing • Autoboxing is the automatic conversion of a primitive value to a corresponding wrapper object: Integer obj; int num = 42; obj = int; • The assignment creates the appropriate Integer object • The reverse conversion (called unboxing) also occurs automatically as needed © 2004 Pearson Addison-Wesley. All rights reserved 32
Real Estate Commission Calculator • Write a program that calculates the dollar amount of the commission based on user input § Input: address, price, and commission percentage • price: leading $ and no commas to group digits • commission: percentage with a trailing % § Example: “ 5423 Seabrook Ave. $250000 5. 5%” § Display the result in a popup window © 2004 Pearson Addison-Wesley. All rights reserved 33
- Slides: 33