Download presentation
Presentation is loading. Please wait.
Published byGeorge McGarry Modified over 9 years ago
1
3. Using Classes And Objects Based on Java Software Development, 5 th 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 A variable can have value of Primitive type—e.g., int count; Primitive type—e.g., int count; Reference to an object—e.g. String city; Reference to an object—e.g. String city; A reference value is an address of memory location. A reference value is an address of memory location. The declaration above does not yet create an object. 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”) 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(); 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. Invoking object name to execute its method length(), returning the number of characters in the object. Java Standard Class Library (API) Java Standard Class Library (API)Standard Class Library Standard Class Library
6
6 References Note that a primitive variable contains the value itself, but an object variable contains the address of the object 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 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 graphically Rather than dealing with arbitrary addresses, we often depict a reference graphically "Steve Jobs" String name int num 38
7
7 Assignment Revisited The act of assignment takes a copy of a value and stores it in a variable The act of assignment takes a copy of a value and stores it in a variable For primitive types: For primitive types: num1 38 num2 96 Before: num2 = num1; num1 38 num2 38 After:
8
8 Reference Assignment For object references, assignment copies the address: For object references, assignment copies the address: name2 = name1; name1 name2 Before: "Steve Jobs" "Steve Wozniak" name1 name2 After: "Steve Jobs" "Steve Wozniak"
9
Aliases Aliases—two or more references that refer to the same object String me, you; me = new String(“Tom Jones”); you = me; // you now points to // same object you = “Patty Duke”; // now, you and me both // point to “Patty Duk” Aliases—two or more references that refer to the same object String me, you; me = new String(“Tom Jones”); you = me; // you now points to // same object you = “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” 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. Object that a pointed to originally, “Alice”, has lost its handle and is no longer accessible. Such memory is called “garbage.” Such memory is called “garbage.” Java performs automatic garbage collection. Java performs automatic garbage collection. Other languages, e.g., C++, require the programmer to code 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: Class String is used so often that Java allows short cut. Given: String s: s = “Some string literal”; in place of s = “Some string literal”; in place of s = new String(“Some string literal”); s = new String(“Some string literal”); This is allowed only for String. This is allowed only for String.
13
String Method indexOf(char ch) indexOf(char ch) returns the position of the first occurrence of character ch in a String object 0 1 2 012345678901234567890 Kaimuki, Honolulu, HI returns the position of the first occurrence of character ch in a String object 0 1 2 012345678901234567890 Kaimuki, Honolulu, HI String place = new String(“Kaimuki, …”); char ch = ‘k’; int pos = place.indexOf(ch); // pos = 5 StringMutation.java StringMutation.java StringMutation.java
14
Your Turn Problem: Given a name in lastName- comma-space-firstName format, print it in firstName-space-lastName format. Problem: Given a name in lastName- comma-space-firstName format, print it in firstName-space-lastName format. String name = “Chang, Charles”; String name = “Chang, Charles”; Solution Solution posComma position of ‘,’ posComma position of ‘,’ posBlank position of blank posBlank position of blank Len length of string 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 Class Library a collection of classes that we can use when developing programs a collection of classes that we can use when developing programs Java Standard Class Library Java Standard Class Library part of any Java development environment, containing hundreds of useful classes part of any Java development environment, containing hundreds of useful classes not part of the Java language, but always available not part of the Java language, but always available Available at: http://java.sun.com/j2se/1.5.0/docs/api/ Available at: http://java.sun.com/j2se/1.5.0/docs/api/ http://java.sun.com/j2se/1.5.0/docs/api/
17
Packages The classes of the Java standard class library are organized into packages The classes of the Java standard class library are organized into packages Some packages in the standard library: 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 package import java.util.Scanner; … Scanner sc = new Scanner(); // import one class in package import java.util.Scanner; … Scanner sc = new Scanner(); // import all classes in package Import java.util.* … Random rnd = new Random(); // import all classes in package Import java.util.* … Random rnd = new Random(); // java.language.* is implicitly // imported System.out.println(“Hello.”); // java.language.* is implicitly // imported System.out.println(“Hello.”);
19
Math Class Math class is in java.language package (which means it is imported implicitly) Math class is in java.language package (which means it is imported implicitly) Math class contains method to find Math class contains method to find Square root Square root Trigonometric relations Trigonometric relations Exponentiation, etc Exponentiation, etc Math class methods are static methods— methods that belong to the class and not to individual objects c = Math.sqrt(a * a + b * b); Math class methods are static methods— methods that belong to the class and not to individual objects c = Math.sqrt(a * a + b * b); RandomNumbers.java RandomNumbers.java RandomNumbers.java Quadratic.java Quadratic.java Quadratic.java Quadratic.java
20
Static Method Instance method Instance method Method that is associated with each instance (object) of a class 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, …” 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 Method which belongs the class and not to each object E.g., Dog.countOf(); // returns of number of instantiations 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 Package java.text contains Class NumberFormat, which contains Class NumberFormat, which contains Static method getCurrencyInstance() Static method getCurrencyInstance() Static method getPercentInstance() Static method getPercentInstance() double result = 0.034567; NumberFormat fmt1 = NumberFormat.getCurrencyInstance(); System.out.println(fmt1.format(result)); // $0.03 NumberFormat fmt2 = NumberFormat.getPercentInstance(); System.out.pringln(fmt2.format(result)); // 3%
23
Formatting Output (cont.) Package java.text also contains Package java.text also contains Class DecimalFormat which can be instantiated in the usual way Class DecimalFormat which can be instantiated in the usual way Purchase.java Purchase.java Purchase.java CircleStats.java CircleStats.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 Enumerated type Allows the programmer to define possible values Allows the programmer to define possible values Promotes understandability of code Promotes understandability of code Restricts possible values for a variable Restricts possible values for a variable E.g. 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.) 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 = 1 String color = light.name(); // color = “green” Enumerated type is like class. Enumerated type is like class. Enumerated type has static methods— ordinal() and name(). Enumerated type has static methods— ordinal() and name(). Icecream.java Icecream.java Icecream.java
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: To make primitive types act like classes: Primitive Type Wrapper Class byteByte shortShort intInteger longLong floatFloat doubleDouble charCharacter booleanBoolean voidVoid
29
Wrapper Class (cont.) To create an integer object: Integer age = new Integer(40); 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 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 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 Classes needed for GUI components found in the following packages java.awt – original package java.awt – original package javax.swing – more versatile classes javax.swing – more versatile classes Both packages are needed to create GUI- based programs Both packages are needed to create GUI- based programs
32
Graphical User Interface (GUI) GUI Container GUI Container A component used to contain other components A component used to contain other components Frame Frame A container used to display as a separate window—has title, can resize, can scroll A container used to display as a separate window—has title, can resize, can scroll Panel Panel Cannot itself display—must be contained in a container, e.g., frae Cannot itself display—must be contained in a container, e.g., frae Used to organize other components Used to organize other components
33
Label, TextField All GUI componets—Label, TextField, Panel, Frame—are found in both java.awt and javax.swing. All GUI componets—Label, TextField, Panel, Frame—are found in both java.awt and javax.swing. For consistency, stay with javax.swing. For consistency, stay with javax.swing. Label Label Used to display text, image, or both, which cannot be edited Used to display text, image, or both, which cannot be edited TextField TextField Used to display text for input or editing Used to display text for input or editing Authority.java Authority.java Authority.java
34
Nested Panels Panels can be nested within another panel, which can all be inserted into a fram 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 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 NestedPanels.java 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. JLabel object can contain text, image, or both. import javax.swing.*; … JImageIcon img = new JImageIcon(“mypic.gif”); JLabel aLabel = new JLabel(img); import javax.swing.*; … JImageIcon img = new JImageIcon(“mypic.gif”); JLabel aLabel = new JLabel(img); LabelDemo.java LabelDemo.java LabelDemo.java
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.