1 / 36

3. Using Classes And Objects

3. Using Classes And Objects. Based on Java Software Development, 5 th Ed. By Lewis &Loftus. Topics. Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images. Creating Objects. A variable can have value of

Télécharger la présentation

3. Using Classes And Objects

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. 3. Using Classes And Objects Based on Java Software Development, 5th Ed. By Lewis &Loftus

  2. Topics Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images

  3. Creating Objects • A variable can have value of • Primitive type—e.g.,int count; • Reference to an object—e.g.String city; • A reference value is an address of memory location. • The declaration above does not yet create an object.

  4. Creating Objects (cont.) • To create an object of class String:String city = new String(“Hilo”) • Instantiation—creating an object of a particular class Key word Special method—called Constructor to create a new object

  5. Invoking Methods • Class String has dozens of methods defined—indexOf(), substring(), trim(), length(), etc.String name = new String(“San Jose”);int count = name.length(); • Invoking object name to execute its method length(), returning the number of characters in the object. • Java Standard Class Library (API)

  6. 38 int num "SteveJobs" String name 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

  7. 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;

  8. "Steve Jobs" name1 Before: "SteveWozniak" name2 "SteveJobs" name1 After: "SteveWozniak" name2 Reference Assignment • For object references, assignment copies the address: name2 = name1;

  9. Aliases • Aliases—two or more references that refer to the same objectString me, you;me = new String(“Tom Jones”);you = me; // you now points to // same objectyou = “Patty Duke”; // now, you and me both // point to “Patty Duk”

  10. Garbage Collection • String a = new String (“Alice”);String b = new String (“Beth”);a = b; // a & b point to “Beth” • Object that a pointed to originally, “Alice”, has lost its handle and is no longer accessible. • Such memory is called “garbage.” • Java performs automatic garbage collection. • Other languages, e.g., C++, require the programmer to code garbage collection

  11. Topics Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images

  12. String Class • Class String is used so often that Java allows short cut. Given: String s: • s = “Some string literal”; in place of • s = new String(“Some string literal”); • This is allowed only for String.

  13. String Method • indexOf(char ch) • returns the position of the first occurrence of character ch in a String object0 1 2012345678901234567890Kaimuki, Honolulu, HI String place = new String(“Kaimuki, …”); char ch = ‘k’; int pos = place.indexOf(ch); // pos = 5 • StringMutation.java

  14. Your Turn • Problem: Given a name in lastName-comma-space-firstName format, print it in firstName-space-lastName format. • String name = “Chang, Charles”; • Solution • posComma  position of ‘,’ • posBlank  position of blank • Len  length of string

  15. Topics Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images

  16. Class Library • Class Library • a collection of classes that we can use when developing programs • Java Standard Class Library • part of any Java development environment, containing hundreds of useful classes • not part of the Java language, but always available • Available at: http://java.sun.com/j2se/1.5.0/docs/api/

  17. Packages • The classes of the Java standard class library are organized into packages • Some packages in the standard library: 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

  18. Importing Packages • // import one class in packageimport java.util.Scanner;…Scanner sc = new Scanner(); • // import all classes in packageImport java.util.*…Random rnd = new Random(); • // java.language.* is implicitly// importedSystem.out.println(“Hello.”);

  19. Math Class • Math class is in java.language package (which means it is imported implicitly) • Math class contains method to find • Square root • Trigonometric relations • Exponentiation, etc • Math class methods are static methods—methods that belong to the class and not to individual objectsc = Math.sqrt(a * a + b * b); • RandomNumbers.java • Quadratic.java

  20. Static Method • Instance method • Method that is associated with each instance (object) of a class • E.g.,Dog fido = new Dog();Dog lassie = new Dog();fido.bark(“bow”); // barks “bow, bow, …”lassie.bark(“oof””); // barks “oof, oof, …” • Method which belongs the class and not to each object • E.g.,Dog.countOf(); // returns of number of instantiations

  21. Topics Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images

  22. Formatting Output • Package java.text contains • Class NumberFormat, whichcontains • Static method getCurrencyInstance() • Static method getPercentInstance() double result = 0.034567;NumberFormat fmt1 = NumberFormat.getCurrencyInstance();System.out.println(fmt1.format(result)); // $0.03NumberFormat fmt2 = NumberFormat.getPercentInstance();System.out.pringln(fmt2.format(result)); // 3%

  23. Formatting Output (cont.) • Package java.text also contains • Class DecimalFormatwhich can be instantiated in the usual way • Purchase.java • CircleStats.java double result = 12.34567;DecimalFormat fmt = new DecimalFormat(“0.##”);System.out.println(“Result: “ + fmt.format(result); // 12.34

  24. Topics Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images

  25. Enumerated Types • Enumerated type • Allows the programmer to define possible values • Promotes understandability of code • Restricts possible values for a variable • E.g. enum Season (spring, summer, fall, winter);enum TrafficLight (red, orange, green);Season current;TrafficLight light;current = Season.summer;light = TrafficLight.green;

  26. Enumerated Types (cont.) • Enumerated type is like class. • Enumerated type has static methods—ordinal() and name(). • Icecream.java enum Season (spring, summer, fall, winter);enum TrafficLight (red, orange, green);Season current;TrafficLight light;current = Season.summer;light = TrafficLight.green; int pos = current.ordinal(); // pos = 1String color = light.name(); // color = “green”

  27. Topics Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images

  28. Wrapper Class • To make primitive types act like classes:

  29. Wrapper Class (cont.) • To create an integer object:Integer age = new Integer(40); • Static method to convert String to Integer:int num;String sNum = “125”;num = Integer.parseInt(sNum); // num = 125 • Wrapper classes have some useful constants: In Integer class, MAX_VALUE & MIN_VALUE contain largest and smallest int values

  30. Topics Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images

  31. Graphical User Interface (GUI) • Classes needed for GUI components found in the following packages • java.awt – original package • javax.swing – more versatile classes • Both packages are needed to create GUI-based programs

  32. Graphical User Interface (GUI) • GUI Container • A component used to contain other components • Frame • A container used to display as a separate window—has title, can resize, can scroll • Panel • Cannot itself display—must be contained in a container, e.g., frae • Used to organize other components

  33. Label, TextField • All GUI componets—Label, TextField, Panel, Frame—are found in both java.awt and javax.swing. • For consistency, stay with javax.swing. • Label • Used to display text, image, or both, which cannot be edited • TextField • Used to display text for input or editing • Authority.java

  34. Nested Panels • Panels can be nested within another panel, which can all be inserted into a fram • import javax.swing.*;…JFrame frame = new JFrame();JPanel p1 = new JPanel();JPanel p2 = new JPanel();-- add label, textField, etc, to p1-- add label, textField, etc, to p2-- add p1 and p2 to frame • NestedPanels.java

  35. Topics Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images

  36. Images • JLabel object can contain text, image, or both. • import javax.swing.*;…JImageIcon img = new JImageIcon(“mypic.gif”);JLabel aLabel = new JLabel(img); • LabelDemo.java

More Related