Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 3 Using Classes and Objects. © 2004 Pearson Addison-Wesley. All rights reserved3-2 Using Classes and Objects We can create more interesting programs.

Similar presentations


Presentation on theme: "Chapter 3 Using Classes and Objects. © 2004 Pearson Addison-Wesley. All rights reserved3-2 Using Classes and Objects We can create more interesting programs."— Presentation transcript:

1 Chapter 3 Using Classes and Objects

2 © 2004 Pearson Addison-Wesley. All rights reserved3-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

3 © 2004 Pearson Addison-Wesley. All rights reserved3-3 Outline Creating Objects The GregorianCalendar Class The String Class Wrapper Classes Next Class: Packages Formatting Output Enumerated Types

4 © 2004 Pearson Addison-Wesley. All rights reserved3-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

5 © 2004 Pearson Addison-Wesley. All rights reserved3-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 is a special method that sets up the object Creating an object is called instantiation An object is an instance of a particular class

6 © 2004 Pearson Addison-Wesley. All rights reserved3-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

7 © 2004 Pearson Addison-Wesley. All rights reserved3-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

8 © 2004 Pearson Addison-Wesley. All rights reserved3-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 96 Before: num2 = num1; num1 38 num2 38 After:

9 © 2004 Pearson Addison-Wesley. All rights reserved3-9 Reference Assignment For object references, assignment copies the address: name2 = name1; name1 name2 Before: "Steve Jobs" "Steve Wozniak" name1 name2 After: "Steve Jobs"

10 © 2004 Pearson Addison-Wesley. All rights reserved3-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

11 © 2004 Pearson Addison-Wesley. All rights reserved3-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

12 © 2004 Pearson Addison-Wesley. All rights reserved3-12 Outline Creating Objects The GregorianCalendar Class The String Class Wrapper Classes

13 © 2004 Pearson Addison-Wesley. All rights reserved3-13 Example of a Mutable Class GregorianCalendar  Defined in java.util  Contains several constructors GregorianCalendar()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)GregorianCalendar –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)GregorianCalendar – Constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale.

14 © 2004 Pearson Addison-Wesley. All rights reserved3-14 More on the GregorianCalendar Contains 16 methods  boolean isLeapYear(int year)isLeapYear Determines if the given year is a leap year.  void add(int field, int amount).add Inherits 31 method from the Calendar class  int get(int field)get 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_MONTHYEARMONTHDATEDAY_OF_MONTH DAY_OF_YEARDAY OF WEEKWEEK_OF_YEAR WEEK_OF_MONTH Using the get method  int year = today.get(Calendar.YEAR);

15 © 2004 Pearson Addison-Wesley. All rights reserved3-15 Date Example // Demonstrates the GregorianCalendar, a mutable class import java.util.*; // for GregorianCalendar import 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);

16 © 2004 Pearson Addison-Wesley. All rights reserved3-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);

17 © 2004 Pearson Addison-Wesley. All rights reserved3-17 Primitive Types vs. Objects with Assignment Statements int x = 5; int y = x; x++; GregorianCalendar d1 = new GregorianCalendar(2005, Caldendar.October, 1); GregorianCalendar d2 = d1; d1.add(Calendar.YEAR, 5);

18 © 2004 Pearson Addison-Wesley. All rights reserved3-18 Fix using clone method GregorianCalendar d1 = new GregorianCalendar(2005, Caldendar.October, 1); GregorianCalendar d2 = (GregorianCalendar) d1.clone(); d1.add(Calendar.YEAR, 5);

19 © 2004 Pearson Addison-Wesley. All rights reserved3-19 Outline Creating Objects The GregorianCalendar Class The String Class Wrapper Classes

20 © 2004 Pearson Addison-Wesley. All rights reserved3-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

21 © 2004 Pearson Addison-Wesley. All rights reserved3-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 http://java.sun.com/j2se/1.5.0/docs/api/index.html

22 © 2004 Pearson Addison-Wesley. All rights reserved3-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

23 © 2004 Pearson Addison-Wesley. All rights reserved3-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);

24 © 2004 Pearson Addison-Wesley. All rights reserved3-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: 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 Output:

25 © 2004 Pearson Addison-Wesley. All rights reserved3-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

26 © 2004 Pearson Addison-Wesley. All rights reserved3-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”;

27 © 2004 Pearson Addison-Wesley. All rights reserved3-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(“ “);

28 © 2004 Pearson Addison-Wesley. All rights reserved3-28 Outline Creating Objects The GregorianCalendar Class The String Class Wrapper Classes

29 © 2004 Pearson Addison-Wesley. All rights reserved3-29 Wrapper Classes The java.lang package contains wrapper classes that correspond to each primitive type: Primitive TypeWrapper Class byteByte shortShort intInteger longLong floatFloat doubleDouble charCharacter booleanBoolean voidVoid

30 © 2004 Pearson Addison-Wesley. All rights reserved3-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

31 © 2004 Pearson Addison-Wesley. All rights reserved3-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

32 © 2004 Pearson Addison-Wesley. All rights reserved3-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

33 © 2004 Pearson Addison-Wesley. All rights reserved3-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


Download ppt "Chapter 3 Using Classes and Objects. © 2004 Pearson Addison-Wesley. All rights reserved3-2 Using Classes and Objects We can create more interesting programs."

Similar presentations


Ads by Google