chapter 3 using classes and objects. © 2004 pearson addison-wesley. all rights reserved3-2 using...
TRANSCRIPT
Chapter 3
Using Classes and Objects
© 2004 Pearson Addison-Wesley. All rights reserved 3-2
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 3-3
Outline
Creating Objects
The GregorianCalendar Class
The String Class
Wrapper Classes
Next Class:
Packages
Formatting Output
Enumerated Types
© 2004 Pearson Addison-Wesley. All rights reserved 3-4
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 3-5
Creating Objects
• Generally, we use the new operator to create an object
title = new String ("Java Software Solutions");
This calls the String constructor, which isa 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 3-6
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 3-7
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
"Steve Jobs"name1
num1 38
© 2004 Pearson Addison-Wesley. All rights reserved 3-8
Assignment Revisited
• The act of assignment takes a copy of a value and stores it in a variable
• For primitive types:
num1 38
num2 96Before:
num2 = num1;
num1 38
num2 38After:
© 2004 Pearson Addison-Wesley. All rights reserved 3-9
Reference Assignment
• For object references, assignment copies the address:
name2 = name1;
name1
name2Before:
"Steve Jobs"
"Steve Wozniak"
name1
name2After:
"Steve Jobs"
© 2004 Pearson Addison-Wesley. All rights reserved 3-10
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 only one object
© 2004 Pearson Addison-Wesley. All rights reserved 3-11
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
© 2004 Pearson Addison-Wesley. All rights reserved 3-12
Outline
Creating Objects
The GregorianCalendar Class
The String Class
Wrapper Classes
© 2004 Pearson Addison-Wesley. All rights reserved 3-13
Example of a Mutable Class
• GregorianCalendar Defined in java.util Contains several constructors
• GregorianCalendar() – Constructs a default GregorianCalendar using the
current time in the default time zone with the default locale.
• GregorianCalendar(int year, int month, int date)
– Constructs a GregorianCalendar with the given date set in the default time zone with the default locale.
• GregorianCalendar(int year, int month, int date, int hour, int minute)
– Constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale.
© 2004 Pearson Addison-Wesley. All rights reserved 3-14
More on the GregorianCalendar
• Contains 16 methods boolean isLeapYear(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 3-15
Date Example// Demonstrates the GregorianCalendar, a mutable class
import java.util.*; // for GregorianCalendarimport java.text.*; // for DateFormat Class
public class DateExample{
// Creates a GregorianCalendar object for the quizDay, 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
int month, day; // store date attributes
GregorianCalendar quizDay = new GregorianCalendar(2005, Calendar.OCTOBER, 1);
© 2004 Pearson Addison-Wesley. All rights reserved 3-16
Date Example // Get integer value for the characteristics day = System.out.println("Day: " + day); month = System.out.println("Month: " + month);
// Make the quiz 4 days earlier
// Get the new date day = System.out.println("Day 50 days after the quiz: " + day); month = System.out.println("Month 50 days after the quiz: " + month ); // Format the output of the date using DateFormat DateFormat fmt = DateFormat.getInstance(); System.out.println("Formatted Date: " + fmt.format(quizDay.getTime())); }}
quizDay.get(Calendar.DAY_OF_MONTH);
quizDay.get(Calendar.MONTH);
quizDay.add(Calendar.DAY_OF_MONTH, -4);
quizDay.get(Calendar.DAY_OF_MONTH);
quizDay.get(Calendar.MONTH);
© 2004 Pearson Addison-Wesley. All rights reserved 3-17
Primitive Types vs. Objects with Assignment Statementsint x = 5;
int y = x;
x++;
GregorianCalendar d1 = new GregorianCalendar(2005, Caldendar.October, 1);
GregorianCalendar d2 = d1;
d1.add(Calendar.YEAR, 5);
© 2004 Pearson Addison-Wesley. All rights reserved 3-18
Fix using clone method
GregorianCalendar d1 = new GregorianCalendar(2005, Caldendar.October, 1);
GregorianCalendar d2 = (GregorianCalendar) d1.clone();
d1.add(Calendar.YEAR, 5);
© 2004 Pearson Addison-Wesley. All rights reserved 3-19
Outline
Creating Objects
The GregorianCalendar Class
The String Class
Wrapper Classes
© 2004 Pearson Addison-Wesley. All rights reserved 3-20
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 3-21
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/j2se/1.5.0/docs/api/index.html
© 2004 Pearson Addison-Wesley. All rights reserved 3-22
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 3-23
//*************************************************************// StringMutation.java Author: Lewis/Loftus//// Demonstrates the use of the String class and its methods.//*************************************************************
public class StringMutation{ //---------------------------------------------------------- // Prints a string and various mutations of it. //---------------------------------------------------------- public static void main (String[] args) { String phrase = "Change is inevitable"; String mutation1, mutation2, mutation3, mutation4;
System.out.println ("Original string: \"" + phrase + "\""); System.out.println ("Length of string: " + phrase.length());
mutation1 = phrase.concat(", except from vending machines."); mutation2 = mutation1.toUpperCase(); mutation3 = mutation2.replace ('E', 'X'); mutation4 = mutation3.substring (3, 30);
© 2004 Pearson Addison-Wesley. All rights reserved 3-24
// Print each mutated string System.out.println ("Mutation #1: " + mutation1); System.out.println ("Mutation #2: " + mutation2); System.out.println ("Mutation #3: " + mutation3); System.out.println ("Mutation #4: " + mutation4);
System.out.println ("Mutated length: " + mutation4.length()); }}
Original string: "Change is inevitable"Length of string: 20Mutation #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 FMutated length: 27
Output:
© 2004 Pearson Addison-Wesley. All rights reserved 3-25
String Methods (We are interested in) • str.length() – returns int • str.charAt(int) – returns char• str.substring(int) or str.substring(int, int) – returns
String • str.indexOf(String) or str.indexOf(String, int) – returns
int
• str.lastIndexOf(String)or str.lastIndexOf(String, int) – returns int
• str.toUpperCase() – returns String• str.toLowerCase() – returns String • str.trim() – returns String
© 2004 Pearson Addison-Wesley. All rights reserved 3-26
Storing and Displaying Method Results
• Use assignment statements to store the result of a method call int posBlank = saying.indexOf(“ “);
•
String firstWord = saying.indexOf(0, posBlank);
•
• Including the method call in the output statement System.out.println (“The second blank is at position “ + saying.indexOf(“ “, 4));
String saying = “All roads lead to Rome”;
© 2004 Pearson Addison-Wesley. All rights reserved 3-27
Tricks of the trade
• Use the results of one method as the input to another
char last = str.charAt(str.length()-1);
• Concatenating methods together int endFirstWord = str.trim().indexOf(“ “);
© 2004 Pearson Addison-Wesley. All rights reserved 3-28
Outline
Creating Objects
The GregorianCalendar Class
The String Class
Wrapper Classes
© 2004 Pearson Addison-Wesley. All rights reserved 3-29
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 3-30
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 3-31
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.parseInt(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 3-32
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 3-33
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