360 likes | 519 Views
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
E N D
3. Using Classes And Objects Based on Java Software Development, 5th 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 • 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.
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
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)
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
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;
"Steve Jobs" name1 Before: "SteveWozniak" name2 "SteveJobs" name1 After: "SteveWozniak" name2 Reference Assignment • For object references, assignment copies the address: name2 = name1;
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”
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
Topics Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images
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.
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
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
Topics Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images
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/
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
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.”);
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
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
Topics Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images
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%
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
Topics Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images
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;
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”
Topics Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images
Wrapper Class • To make primitive types act like classes:
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
Topics Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images
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
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
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
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
Topics Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images
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