36
3. Using Classes 3. Using Classes And Objects And Objects Based on Based on Java Software Development, 5 Java Software Development, 5 th th Ed. Ed. By Lewis &Loftus By Lewis &Loftus

3. Using Classes And Objects

Embed Size (px)

DESCRIPTION

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 - PowerPoint PPT Presentation

Citation preview

3. Using Classes 3. Using Classes And ObjectsAnd Objects

Based on Based on Java Software Development, 5Java Software Development, 5thth Ed. Ed.

By Lewis &LoftusBy Lewis &Loftus

TopicsTopicsCreating Objects

The String Class

Packages

Formatting Output

Enumerated Types

Wrapper Classes

Components and Containers

Images

Creating ObjectsCreating Objects

A variable can have value ofA variable can have value of Primitive type—e.g.,Primitive type—e.g.,int count;int count;

Reference to an object—e.g.Reference to an object—e.g.String city;String city;

A reference value is an A reference value is an addressaddress of of memory location.memory location.

The declaration above does not yet The declaration above does not yet create an object.create an object.

Creating Objects (cont.)Creating Objects (cont.)

To create an object of class String:To create an object of class String:

String city = new String(“Hilo”)String city = new String(“Hilo”)

InstantiationInstantiation—creating an object of a —creating an object of a particular classparticular class

Key word

Special method—called Constructor to create a new object

Invoking MethodsInvoking Methods

Class Class StringString has dozens of methods has dozens of methods defined—indexOf(), substring(), trim(), defined—indexOf(), substring(), trim(), length(), etc.length(), etc.

String name = new String(“San Jose”);String name = new String(“San Jose”);int count = name.length();int count = name.length();

Invoking objectInvoking object name name to execute its to execute its methodmethod length() length(), returning the number , returning the number of characters in the object.of characters in the object.

Java Java Standard Class Library (API)(API)

6

ReferencesReferences Note that a primitive variable contains the Note that a primitive variable contains the

value itself, but an object variable contains value itself, but an object variable contains the address of the objectthe address of the object

An object reference can be thought of as a An object reference can be thought of as a pointer to the location of the objectpointer to the location of the object

Rather than dealing with arbitrary Rather than dealing with arbitrary addresses, we often depict a addresses, we often depict a reference graphicallygraphically

"Steve Jobs"String name

int num 38

7

Assignment RevisitedAssignment Revisited

The act of assignment takes a copy of a value The act of assignment takes a copy of a value and stores it in a variableand stores it in a variable

For primitive types:For primitive types:

num1 38

num2 96Before:

num2 = num1;

num1 38

num2 38After:

8

Reference AssignmentReference Assignment

For object references, assignment For object references, assignment copies the address:copies the address:

name2 = name1;

name1

name2Before:

"Steve Jobs"

"Steve Wozniak"

name1

name2After:

"Steve Jobs"

"Steve Wozniak"

AliasesAliases

Aliases—two or more references that Aliases—two or more references that refer to the same objectrefer to the same object

String me, you;String me, you;me = new String(“Tom Jones”);me = new String(“Tom Jones”);you = me; // you now points to you = me; // you now points to // same object // same objectyou = “Patty Duke”;you = “Patty Duke”; // now, you and me both // now, you and me both // point to “Patty Duk” // point to “Patty Duk”

Garbage CollectionGarbage Collection String a = new String (“Alice”);String a = new String (“Alice”);String b = new String (“Beth”);String b = new String (“Beth”);a = b; // a & b point to “Beth”a = b; // a & b point to “Beth”

Object that Object that aa pointed to originally, pointed to originally, “Alice”, has lost its handle and is no “Alice”, has lost its handle and is no longer accessible.longer accessible.

Such memory is called “garbage.”Such memory is called “garbage.” Java performs automatic garbage Java performs automatic garbage

collection.collection. Other languages, e.g., C++, require Other languages, e.g., C++, require

the programmer to code garbage the programmer to code garbage collectioncollection

TopicsTopicsCreating Objects

The String Class

Packages

Formatting Output

Enumerated Types

Wrapper Classes

Components and Containers

Images

String ClassString Class

Class String is used so often that Java Class String is used so often that Java allows short cut. Given: allows short cut. Given: String s:String s: s = “Some string literal”;s = “Some string literal”; in place of 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.

String MethodString Method indexOf(char ch)indexOf(char ch)

returns the position of the first occurrence returns the position of the first occurrence of character of character chch in a String object in a String object

0 1 20 1 2012345678901234567890012345678901234567890Kaimuki, Honolulu, HIKaimuki, Honolulu, HI

String place = new String(“Kaimuki, …”);String place = new String(“Kaimuki, …”);char ch = ‘k’;char ch = ‘k’;int pos = place.indexOf(ch); // pos = int pos = place.indexOf(ch); // pos = 55

StringMutation.java

Your TurnYour Turn

Problem: Given a name in Problem: Given a name in lastName-lastName-comma-space-firstNamecomma-space-firstName format, print format, print it in it in firstName-space-lastNamefirstName-space-lastName format.format.

String name = “Chang, Charles”;String name = “Chang, Charles”;

SolutionSolution posComma posComma position of ‘,’ position of ‘,’ posBlank posBlank position of blank position of blank Len Len length of string length of string

TopicsTopicsCreating Objects

The String Class

Packages

Formatting Output

Enumerated Types

Wrapper Classes

Components and Containers

Images

Class LibraryClass Library

Class LibraryClass Library a collection of classes that we can use when a collection of classes that we can use when

developing programsdeveloping programs Java Standard Class LibraryJava Standard Class Library

part of any Java development environment, part of any Java development environment, containing hundreds of useful classescontaining hundreds of useful classes

not part of the Java language, but always not part of the Java language, but always availableavailable

Available at: Available at: http://java.sun.com/j2se/1.5.0/docs/api/http://java.sun.com/j2se/1.5.0/docs/api/

PackagesPackages

The classes of the Java standard The classes of the Java standard class library are organized into class library are organized into packagespackages

Some packages in the standard Some packages in the standard library:library:

Package

java.langjava.appletjava.awtjavax.swingjava.netjava.utiljavax.xml.parsers

Purpose

General supportCreating applets for the webGraphics and graphical user interfacesAdditional graphics capabilitiesNetwork communicationUtilitiesXML document processing

Importing PackagesImporting Packages

// import one class in package// import one class in packageimport java.util.Scanner;import java.util.Scanner;……Scanner sc = new Scanner();Scanner sc = new Scanner();

// import all classes in package// import all classes in packageImport java.util.*Import java.util.*……Random rnd = new Random();Random rnd = new Random();

// java.language.* is implicitly// java.language.* is implicitly// imported// importedSystem.out.println(“Hello.”);System.out.println(“Hello.”);

Math ClassMath Class Math class is in java.language package Math class is in java.language package

(which means it is imported implicitly)(which means it is imported implicitly) Math class contains method to findMath class contains method to find

Square rootSquare root Trigonometric relationsTrigonometric relations Exponentiation, etcExponentiation, etc

Math class methods are static methods—Math class methods are static methods—methods that belong to the class and not methods that belong to the class and not to individual objectsto individual objects

c = Math.sqrt(a * a + b * b);c = Math.sqrt(a * a + b * b); RandomNumbers.javaRandomNumbers.java Quadratic.javaQuadratic.java

Static MethodStatic Method Instance methodInstance method

Method that is associated with each instance Method that is associated with each instance (object) of a class(object) of a class

E.g.,E.g.,Dog fido = new Dog();Dog fido = new Dog();Dog lassie = new Dog();Dog lassie = new Dog();fido.bark(“bow”); // barks “bow, bow, …”fido.bark(“bow”); // barks “bow, bow, …”lassie.bark(“oof””); // barks “oof, oof, …”lassie.bark(“oof””); // barks “oof, oof, …”

Method which belongs the class and not to Method which belongs the class and not to each objecteach object E.g.,E.g.,

Dog.countOf(); // returns of number of Dog.countOf(); // returns of number of instantiationsinstantiations

TopicsTopicsCreating Objects

The String Class

Packages

Formatting Output

Enumerated Types

Wrapper Classes

Components and Containers

Images

Formatting OutputFormatting Output Package Package java.textjava.text contains contains

Class Class NumberFormat, NumberFormat, whichwhich containscontains Static method Static method getCurrencyInstance()getCurrencyInstance() Static method Static method getPercentInstance()getPercentInstance()

double result = 0.034567;double result = 0.034567;NumberFormat fmt1 = NumberFormat fmt1 = NumberFormat.getCurrencyInstance(); NumberFormat.getCurrencyInstance();System.out.println(fmt1.format(result));System.out.println(fmt1.format(result)); // $0.03 // $0.03NumberFormat fmt2 =NumberFormat fmt2 = NumberFormat.getPercentInstance(); NumberFormat.getPercentInstance();System.out.pringln(fmt2.format(result));System.out.pringln(fmt2.format(result)); // 3% // 3%

Formatting Output Formatting Output (cont.)(cont.)

Package Package java.textjava.text also contains also contains Class Class DecimalFormatDecimalFormatwhich can be instantiated in the usual which can be instantiated in the usual wayway

Purchase.javaPurchase.java CircleStats.javaCircleStats.java

double result = 12.34567;double result = 12.34567;DecimalFormat fmt = new DecimalFormat(“0.##”);DecimalFormat fmt = new DecimalFormat(“0.##”);System.out.println(“Result: “ System.out.println(“Result: “ + fmt.format(result); + fmt.format(result); // 12.34 // 12.34

TopicsTopicsCreating Objects

The String Class

Packages

Formatting Output

Enumerated Types

Wrapper Classes

Components and Containers

Images

Enumerated TypesEnumerated Types Enumerated typeEnumerated type

Allows the programmer to define Allows the programmer to define possible valuespossible values

Promotes understandability of codePromotes understandability of code Restricts possible values for a variableRestricts possible values for a variable

E.g.E.g.

enum Season (spring, summer, fall, winter);enum Season (spring, summer, fall, winter);enum TrafficLight (red, orange, green);enum TrafficLight (red, orange, green);Season current;Season current;TrafficLight light;TrafficLight light;current = Season.summer;current = Season.summer;light = TrafficLight.green;light = TrafficLight.green;

Enumerated Types (cont.)Enumerated Types (cont.)

enum Season (spring, summer, fall, winter);enum Season (spring, summer, fall, winter);enum TrafficLight (red, orange, green);enum TrafficLight (red, orange, green);Season current;Season current;TrafficLight light;TrafficLight light;current = Season.summer;current = Season.summer;light = TrafficLight.green;light = TrafficLight.green;

int pos = current.ordinal(); // pos = 1int pos = current.ordinal(); // pos = 1String color = light.name(); String color = light.name(); // color = “green” // color = “green”

Enumerated type is like class.Enumerated type is like class. Enumerated type has static methodsEnumerated type has static methods

—ordinal() and name().—ordinal() and name(). Icecream.javaIcecream.java

TopicsTopicsCreating Objects

The String Class

Packages

Formatting Output

Enumerated Types

Wrapper Classes

Components and Containers

Images

Wrapper ClassWrapper Class To make primitive types act like classes:To make primitive types act like classes:

Primitive TypePrimitive Type Wrapper ClassWrapper Class

bytebyte ByteByte

shortshort ShortShort

intint IntegerInteger

longlong LongLong

floatfloat FloatFloat

doubledouble DoubleDouble

charchar CharacterCharacter

booleanboolean BooleanBoolean

voidvoid VoidVoid

Wrapper Class (cont.)Wrapper Class (cont.) To create an integer object:To create an integer object:Integer age = new Integer(40);Integer age = new Integer(40);

Static method to convert String to Static method to convert String to Integer:Integer:int num;int num;String sNum = “125”;String sNum = “125”;num = Integer.parseInt(sNum); // num = 125num = Integer.parseInt(sNum); // num = 125

Wrapper classes have some useful Wrapper classes have some useful constants: In Integer class, constants: In Integer class, MAX_VALUEMAX_VALUE & & MIN_VALUEMIN_VALUE contain largest and smallest contain largest and smallest intint values values

TopicsTopicsCreating Objects

The String Class

Packages

Formatting Output

Enumerated Types

Wrapper Classes

Components and Containers

Images

Graphical User Interface Graphical User Interface (GUI)(GUI)

Classes needed for GUI components Classes needed for GUI components found in the following packagesfound in the following packages java.awtjava.awt – original package – original package javax.swingjavax.swing – more versatile classes – more versatile classes

Both packages are needed to create Both packages are needed to create GUI-based programsGUI-based programs

Graphical User Interface Graphical User Interface (GUI)(GUI)

GUI ContainerGUI Container A component used to contain other A component used to contain other

componentscomponents FrameFrame

A container used to display as a A container used to display as a separate window—has title, can resize, separate window—has title, can resize, can scrollcan scroll

PanelPanel Cannot itself display—must be Cannot itself display—must be

contained in a container, e.g., fraecontained in a container, e.g., frae Used to organize other componentsUsed to organize other components

Label, TextFieldLabel, TextField

All GUI componets—Label, TextField, All GUI componets—Label, TextField, Panel, Frame—are found in both java.awt Panel, Frame—are found in both java.awt and javax.swing.and javax.swing.

For consistency, stay with javax.swing.For consistency, stay with javax.swing. LabelLabel

Used to display text, image, or both, which Used to display text, image, or both, which cannot be editedcannot be edited

TextFieldTextField Used to display text for input or editingUsed to display text for input or editing Authority.javaAuthority.java

Nested PanelsNested Panels

Panels can be nested within another Panels can be nested within another panel, which can all be inserted into panel, which can all be inserted into a frama fram

import javax.swing.*;import javax.swing.*;……JFrame frame = new JFrame();JFrame frame = new JFrame();JPanel p1 = new JPanel();JPanel p1 = new JPanel();JPanel p2 = new JPanel();JPanel p2 = new JPanel();-- add label, textField, etc, to p1-- add label, textField, etc, to p1-- add label, textField, etc, to p2-- add label, textField, etc, to p2-- add p1 and p2 to frame-- add p1 and p2 to frame

NestedPanels.javaNestedPanels.java

TopicsTopicsCreating Objects

The String Class

Packages

Formatting Output

Enumerated Types

Wrapper Classes

Components and Containers

Images

ImagesImages

JLabel object can contain text, image, or JLabel object can contain text, image, or both.both.

import javax.swing.*;import javax.swing.*;……JImageIcon img = new JImageIcon(“mypic.gif”);JImageIcon img = new JImageIcon(“mypic.gif”);JLabel aLabel = new JLabel(img);JLabel aLabel = new JLabel(img);

LabelDemo.javaLabelDemo.java