1 / 43

Chapter 3

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

hien
Download Presentation

Chapter 3

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 3 Using Classes and Objects

  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 Random and Math classes • formatting output • enumerated types • wrapper classes © 2004 Pearson Addison-Wesley. All rights reserved

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

  4. Creating Objects • A variable holds either a primitive type or a reference to an object x is primitive: int x = 4; • A class name can be used as a type to declare an objectreferencevariable. String is a class. String title; title is a ‘reference’ to an object. • No object is created with this declaration. Title names an object to be created. • An object reference variable holds the address of an object, once the object is created. • The object itself must be created separately © 2004 Pearson Addison-Wesley. All rights reserved

  5. Creating Objects • Generally, we use the new operator to create an object, as in: String title; 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

  6. More on String Objects • Unlike other objects, String objects are special and we have some short forms to create String objects. • (NB Strings are objects, not primitives!!) • E.g. • String name = “Joseph”; • name is a Stringreference that points to a storage location that contains the characters ‘Joseph.’ • Creates a string name whose value is Joseph. • Same as: String name = new String (“Joseph”); • In String objects, we don’t have to cite ‘new’ operator. • Only String is special like this. • All other objects created require the ‘new’ operator. • Above in new String (“Joseph”); the “Joseph” is a parameter sent to String’s constructor. As a parameter, it must be enclosed in parentheses; Because the parameter is a String, it must include the double quotes. © 2004 Pearson Addison-Wesley. All rights reserved

  7. Invoking Methods • We've seen that once an object has been created. Together with the object name, we use the dot operatorto invoke its methods count = title.length() • Note first that length is a method! (How can you tell?) • A method mayreturn a value, which can be used in an assignment or expression • Some methods do not ‘return’ primitives or objects. • A method invocation can be thought of as asking an object (title) to perform a service (return the length of title) to me. (The number of characters in title is assigned to count by the assignment statement.) © 2004 Pearson Addison-Wesley. All rights reserved

  8. 38 num1 Memory address "Steve Jobs" name1 References • Note that a primitive variable contains the value itself, but an object variable contains the address of the object, that is, a ‘reference’ to 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 © 2004 Pearson Addison-Wesley. All rights reserved

  9. 38 num1 Before: 96 num2 38 num1 After: 38 num2 Assignment Revisited • The act of assignment takes a copy of a value and stores it in a variable • For primitive types: num2 = num1; © 2004 Pearson Addison-Wesley. All rights reserved

  10. "Steve Jobs" name1 Before: "Steve Wozniak" name2 "Steve Jobs" name1 After: name2 Reference Assignment • For object references, assignment copies the address: name2 = name1; What happened to the reference to Steve Wozniak? Contents of name2 (an address) was copied into name 1. They now point to the same memory location (aliases) © 2004 Pearson Addison-Wesley. All rights reserved

  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

  12. Outline Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes © 2004 Pearson Addison-Wesley. All rights reserved

  13. 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 (Check this out in NetBeans!) • Each string literal (enclosed in double quotes) represents a String object • Recall: if formally declaring a String object, can use the new operator and the String in quotes in parentheses – the syntax required for creating new objects. © 2004 Pearson Addison-Wesley. All rights reserved

  14. 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 in your book!! • Included methods are: charAt(), compareTo(), concat(), equals(), length() substring(), toLowerCase() and others… • Note: all of these methods require parameters (not shown above). © 2004 Pearson Addison-Wesley. All rights reserved

  15. 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 • Go through StringMutation.java You may see this again. © 2004 Pearson Addison-Wesley. All rights reserved

  16. Outline Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes © 2004 Pearson Addison-Wesley. All rights reserved

  17. Class Libraries • A class library is a collection of classes that we can use when developing programs • The Java standard classlibrary is part of any Java development environment • Not part of the Java language per se, but we rely on them heavily • Various classes we've already used (System , Scanner, String) are part of the Java standard class library • Other class libraries can be obtained through third party vendors, or you can create them yourself © 2004 Pearson Addison-Wesley. All rights reserved

  18. Package  java.lang java.applet java.awt javax.swing java.net  java.util javax.xml.parsers Purpose General support Creating applets for the web Graphics and graphical user interfaces Additional graphics capabilities Network communication Utilities XML document processing Packages • The classes of the Java standard class library are organized into packages • Some of the packages in the standard class library are: © 2004 Pearson Addison-Wesley. All rights reserved

  19. The import Declaration • When you want to use a specificclass from a package when creating objects, you could use its fully qualified name java.util.Scanner • Or you can import the entire class, and then use just the class name import java.util.Scanner; • To import all classes in a particular package, you can use the * wildcard character import java.util.*; © 2004 Pearson Addison-Wesley. All rights reserved

  20. The import Declaration • All classes of the java.lang package are imported automatically into all programs • It's as if all programs contain the following line: import java.lang.*; • That's why we didn't have to import the System or String classes explicitly in earlier programs • The Scanner class, on the other hand, is part of the java.util package, and therefore must be imported if we are to use Scanner and create Scanner objects, as in Scanner scan = new Scanner (System.in); © 2004 Pearson Addison-Wesley. All rights reserved

  21. The Random Class • The Random class is part of the java.util package • It provides methods that generate pseudorandom numbers • A Random object performs complicated calculations based on a seed value to produce a stream of seemingly random values © 2004 Pearson Addison-Wesley. All rights reserved

  22. // RandomNumbers.java Author: Lewis/Loftus // Demonstrates the creation of pseudo-random numbers using the Random class import java.util.Random; public class RandomNumbers { // Generates random numbers in various ranges. public static void main (String[] args) { Random generator = new Random(); // What does this do? int num1; float num2; num1 = generator.nextInt(); // What does this do? System.out.println ("A random integer: " + num1); num1 = generator.nextInt(10); // look up nextInt(10) (p. ??) Get used to doing this… System.out.println ("From 0 to 9: " + num1); num1 = generator.nextInt(10) + 1; System.out.println ("From 1 to 10: " + num1); num1 = generator.nextInt(15) + 20; System.out.println ("From 20 to 34: " + num1); num1 = generator.nextInt(20) - 10; System.out.println ("From -10 to 9: " + num1); num2 = generator.nextFloat(); System.out.println ("A random float (between 0-1): " + num2); num2 = generator.nextFloat() * 6; // 0.0 to 5.999999 num1 = (int)num2 + 1; System.out.println ("From 1 to 6: " + num1); }// end main() }// end class © 2004 Pearson Addison-Wesley. All rights reserved

  23. The Math Class • The Math class is part of the java.lang package • The Math class contains methods that perform various mathematical functions • These include: • absolute value • square root • exponentiation • trigonometric functions © 2004 Pearson Addison-Wesley. All rights reserved

  24. The Math Class • The methods of the Math class are static methods (also called class methods) • Unlike most methods which are invoked via their object name, Staticmethods are invoked using the classname: value = Math.cos(90) + Math.sqrt(delta); • Note: Math is a class…. (note: starts with a capital letter) • See Quadratic.java in your text. • We discuss static methods further in Chapter 6 • Study and understand Quadratic on in your text. © 2004 Pearson Addison-Wesley. All rights reserved

  25. Outline Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes © 2004 Pearson Addison-Wesley. All rights reserved

  26. Formatting Output • It is often necessary to format values in certain ways so that they can be presented properly • The Java standard class library contains classes that provide formatting capabilities. Here are two: • The NumberFormat class allows you to format values as currency or percentages • The DecimalFormat class allows you to format values based on a pattern (the desired format of what you want) •  Both are part of the java.text package, which means you the package to use the • NumberFormat and the • DecimalFormat classes. © 2004 Pearson Addison-Wesley. All rights reserved

  27. Formatting Output: NumberFormat • The NumberFormat class has static methods • They return a “formatter object” • This means that when you invoke a method with the class name, an object is returned. You will then use ‘that’ object and some of ‘its’ methods to format the output as desired. • Here are a couple of the static methods you can get from using objects from NumberFormat class: getCurrencyInstance() getPercentInstance() • Once you get a formatterobjectreturned, a formatter object has a method called format that returns a string with the specified information in the appropriate format • This seems a bit complicated to understand. • Let’s look at some code: Purchase.java © 2004 Pearson Addison-Wesley. All rights reserved

  28. …import java.util.Scanner; Import java.text.NumberFormat; public class Purchase { // note: comments missing – only for spacing on this slide…!!! // Example using NumberFormat formatter objects……. public static void main (String [ ] args) { final double TAX_RATE = 0.06; // 6% sales tax – old! int quantity; double subtotal, tax, totalCost, unitPrice; Scanner scan = new Scanner (System.in); // what does this do? NumberFormat fmt1 = NumberFormat.getCurrencyinstance(); // does what?? NumberFormat fmt2 = NumberFormat.getPercentInstance(); // These last two statements each return an object of type NumberFormat. // We can then use methods in that object to do work for us…  System.out.print (“Enter the quantity: “); // poor prompt! quantity = scan.nextInt(); // assumptions made! System.out.print (“Enter the unit price: “); // another poor prompt. Why? unitPrice = scan.nextDouble(); subtotal- quantity*unitPrice; tax = subtotal * TAX_RATE; totalCost = subtotal + tax; // have computed a subtotal, tax, and a total cost System.out.println (“Subtital: “ + fmt1.format(subtotal)); // using format method in // fmt1 to format output like ‘currency’ should look…. System.out.println (“Tax: “ + fmt1.format(tax) + “ at “ + fmt2.format(TAX_RATE)); // uses object fmt2 to // print out data in a percentage format (see above…) System.out.println (“Total: “ + fmt1.format(totalCost)); } // end main() } // end class © 2004 Pearson Addison-Wesley. All rights reserved

  29. Formatting Output: Decimal Format • The DecimalFormat class can be used to format a floatingpoint value in various ways • For example, you can specify that the number should be truncated to three decimal places •  The constructor of the DecimalFormat class takes a string that represents a pattern for the formatted number • Study and understand previous code. •  Better: Look up Decimal Format and its methods in the Java API (link on my web page). • See CircleStats.java © 2004 Pearson Addison-Wesley. All rights reserved

  30. Decimal Format (from web) Customizing Formats You can use the DecimalFormat class to format decimal numbers. This class allows you to control the display of leading and trailing zeros, prefixes and suffixes, grouping (thousands) separators, and the decimal separator. This class offers a great deal of flexibility in the formatting of numbers, but it can make your code more complex. • The text that follows uses examples that demonstrate the DecimalFormat. • Constructing Patterns • You specify the formatting properties of DecimalFormat with a pattern String. The pattern determines what the formatted number looks like. For a full description of the pattern syntax, see Number Format Pattern Syntax. • The example that follows creates a formatter by passing a pattern String to the DecimalFormat constructor. The format method accepts a double value as an argument and returns the formatted number in a String: • DecimalFormat myFormatter = new DecimalFormat(pattern); • String output = myFormatter.format(value); • System.out.println(value + " " + pattern + " " + output); • The output for the preceding lines of code is described in the following table. The value is the number, a double , that is to be formatted. The pattern is the String that specifies the formatting properties. The output, which is a String, represents the formatted number. © 2004 Pearson Addison-Wesley. All rights reserved

  31. Output from DecimalFormatDemo Program • Value Pattern Output • 123456.789 ###.## 123456.79 • The value has three digits to the right of the decimal point, but the pattern has only two. • The format method handles this by rounding up. • 123.78 000000.000 000123.780 • The pattern specifies leading and trailing zeros, because the 0 character is used instead of the pound sign (#). • 12345.67 $###,###.### $12,345.67 • The first character in the pattern is the dollar sign ($). Note that it immediately precedes the leftmost digit in the formatted output. © 2004 Pearson Addison-Wesley. All rights reserved

  32. Outline Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes © 2004 Pearson Addison-Wesley. All rights reserved

  33. Enumerated Types • Java allows you to define an enumeratedtype, which can then be used to declare variables • An enumerated type establishes all possible values for a variable of that type • The values are identifiers of your own choosing • The following declaration creates an enumerated type called Season enum Season {winter, spring, summer, fall}; • Any number of values can be listed • You are creating your own type of data…and supplying all permissible values. • Note the syntax of enumerated data types above… © 2004 Pearson Addison-Wesley. All rights reserved

  34. Enumerated Types • Once a type is defined, a variable of that type can be declared (liken this to ‘class’ and ‘object’ - sort of...) Season time; So, time is a variable of type Season and can be assigned (can ONLY be assigned) a value such as: time = Season.fall; • The values are specified through the name of the type • Enumerated types are type-safe – you cannot assign any value other than those listed © 2004 Pearson Addison-Wesley. All rights reserved

  35. Ordinal Values • Internally, each value of an enumerated type is stored as an integer, called its ordinal value • The first value in an enumerated type has an ordinal value of zero, the second one, and so on • However, you cannot assign a numeric value to an enumerated type, even if it corresponds to a valid ordinal value © 2004 Pearson Addison-Wesley. All rights reserved

  36. Enumerated Types • The declaration of an enumerated type is a special type of class, and each variable of that type is an object • The ordinal method returns the ordinal value of the object • The name method returns the name of the identifier corresponding to the object's value © 2004 Pearson Addison-Wesley. All rights reserved

  37. … only a segment here… public class IceCream { enum Flavor (vanilla, chocolate, coffee, rockyRoad, cookieDough); public static void main(……) { Flavor cone1, cone2, cone3; // objects of enum type Flavor // This means that cone1, … can only take on values listed in Flavor. cone1 = Flavor.rockyRoad; // assigning values to the objects. cone2 = Flavor.chocolate; System.out.println (“ cone1 value: “ + cone1); //invoking value attribute System.out.println (“ cone1 ordinal: “+ cone1.ordinal() ); System.out.println (“ cone1 name: “ + cone1.name()); // invoking name attribute Outputs: cone1: value: rockyRoad cone1 ordinal: 3 cone name: rockyRoad …. © 2004 Pearson Addison-Wesley. All rights reserved

  38. Outline Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes © 2004 Pearson Addison-Wesley. All rights reserved

  39. Wrapper Classes • The java.lang package contains wrapperclasses that correspond to eachprimitive type: • Note: each Class is capitalized, as all classes are. So, what do wrapper classes do for us? Why do we need them? Why not just use their corresponding primitive?? © 2004 Pearson Addison-Wesley. All rights reserved

  40. Wrapper Classes • The following declaration creates an Integerobject which represents the integer 40 as an object Integer age = new Integer(40); • Discuss this syntax… • Creates an object, age, of type Integer and gives it an initial value of 40. (Constructor assigns value of 40 as part of its initialization – just like an object – later) • 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; that is, have objects within objects. VERY often done, as we’ll see. • Primitive values could not be stored in such containers, but wrapper objects could be. • Then too, some methods in some objects accept only objects and not primitives! • This will become clearer later. But for now, note that primitives have corresponding wrapper classes that in some instances must be used; that is, the corresponding primitive canNOT be used… © 2004 Pearson Addison-Wesley. All rights reserved

  41. Wrapper Classes • Wrapper classes also contain staticmethods 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: int num; num = Integer.parseInt(str); Or float fltnum; fltnum = Float.parseFloat(str); If the input is of the form 13.2, that is nn.n. © 2004 Pearson Addison-Wesley. All rights reserved

  42. More on Wrapper Classes •  Recognize that when you input data from the keyboard, say a 14, it is not a numeric 14. It is a two character (string): a 1 followed by a 4. To use this as a number, it must be converted to an integer. • The previous code will convert a string to an integer or a float. (See previous code) • Scanner does this for us automatically! Unfortunately, this obscures what is actually being done – or, what ‘must’ be done to accept text input from a keyboard and get it into an appropriate numeric form. • 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

  43. Autoboxing • Autoboxing is the automatic conversion of a primitive value to a corresponding wrapper object: Integer obj;// declares a wrapper class int num = 42; obj = num; • The assignment creates the appropriate Integer object • The reverse conversion (called unboxing) also occurs automatically as needed © 2004 Pearson Addison-Wesley. All rights reserved

More Related