Download Using Classes And Objects

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
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”)
Key word
Special method—called
Constructor to create a new
object
 Instantiation—creating an object of a particular
class
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)
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
int num
String name
38
"Steve Jobs"
6
Assignment Revisited


The act of assignment takes a copy of a
value and stores it in a variable
For primitive types:
Before:
num1
38
num2
96
num2 = num1;
After:
num1
38
num2
38
7
Reference Assignment

For object references, assignment copies
the address:
Before:
name1
"Steve Jobs"
name2
"Steve Wozniak"
name2 = name1;
name1
After:
name2
"Steve Jobs"
"Steve Wozniak"
8
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”
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 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
Your Turn

Problem: Given a name in lastNamecomma-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


Java Standard Class Library



a collection of classes that we can use when
developing programs
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
Purpose
java.lang
java.applet
java.awt
javax.swing
java.net
java.util
javax.xml.parsers
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 package
import java.util.Scanner;
…
Scanner sc = new Scanner();
// import all classes in package
Import java.util.*
…
Random rnd = new Random();
// java.language.* is implicitly
// imported
System.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 objects
c = 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, which contains
 Static method getCurrencyInstance()
 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%
Formatting Output (cont.)

Package java.text also contains



Class DecimalFormat
which 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 = 1
String 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:
Primitive Type
Wrapper Class
byte
short
int
Byte
Short
Integer
long
float
double
Long
Float
Double
char
boolean
void
Character
Boolean
Void
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 GUIbased programs
Graphical User Interface (GUI)

GUI Container


Frame


A component used to contain other
components
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