Oracle10g Java Programming Instructor Guide - Volume 2.pdf

Embed Size (px)

Citation preview

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    1/419

    D17249GC11

    Edition 1.1

     August 2004

    D39816

    Oracle10g: Java Programming

    Instructor Guide - Volume 2

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    2/419

    Copyright © 2004, Oracle. All rights reserved.

    This documentation contains proprietary information of Oracle Corporation. It is

    provided under a license agreement containing restrictions on use and disclosure and

    is also protected by copyright law. Reverse engineering of the software is prohibited.

    If this documentation is delivered to a U.S. Government Agency of the Department of

    Defense, then it is delivered with Restricted Rights and the following legend is

    applicable:

    Restricted Rights Legend

    Use, duplication or disclosure by the Government is subject to restrictions for

    commercial computer software and shall be deemed to be Restricted Rights software

    under Federal law, as set forth in subparagraph (c)(1)(ii) of DFARS 252.227-7013,

    Rights in Technical Data and Computer Software (October 1988).

    This material or any portion of it may not be copied in any form or by any means

    without the express prior written permission of Oracle Corporation. Any other copying

    is a violation of copyright law and may result in civil and/or criminal penalties.

    If this documentation is delivered to a U.S. Government Agency not within the

    Department of Defense, then it is delivered with “Restricted Rights,” as defined in

    FAR 52.227-14, Rights in Data-General, including Alternate III (June 1987).

    The information in this document is subject to change without notice. If you find any

    problems in the documentation, please report them in writing to Education Products,

    Oracle Corporation, 500 Oracle Parkway, Box SB-6, Redwood Shores, CA 94065.Oracle Corporation does not warrant that this document is error-free.

     All references to Oracle and Oracle products are trademarks or registered trademarks

    of Oracle Corporation.

     All other products or company names are used for identification purposes only, and

    may be trademarks of their respective owners.

    Authors

    Jeff Gallus

    Glenn Stokol

    Technical Contributors

    and Reviewers

    Kenneth Cooper Peter DriverChristian DugasCraig Hollister Chika IzumiPete LaseauGlenn MaslenMonica MotleyGayathri Rajagopal

    Publisher

    Poornima G

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    3/419

    Preface

    I Introduction

    Objectives I-2

    Course Overview I-3

    1 Introducing the Java and Oracle Platforms

    Objectives 1-2

    What Is Java? 1-3

    Key Benefits of Java 1-4

     An Object-Oriented Approach 1-6

    Platform Independence 1-7

    Using Java with Enterprise Internet Computing 1-8

    Using the Java Virtual Machine 1-10

    How Does JVM Work? 1-12

    Benefits of Just-In-Time (JIT) Compilers 1-14

    Implementing Security in the Java Environment 1-16

    Deployment of Java Applications 1-18

    Using Java with Oracle 10g 1-19

    Java Software Development Kit 1-20

    Using the Appropriate Development Kit 1-21

    Integrated Development Environment 1-22

    Exploring the JDeveloper Environment 1-23

    Oracle10g Products 1-24

    Summary 1-25

    2 Defining Object-Oriented Principles

    Objectives 2-2

    What Is Modeling? 2-4

    What Are Classes and Objects? 2-5

     An Object’s Attributes Maintain Its State 2-6

    Objects Have Behavior 2-8

    Objects Are Modeled as Abstractions 2-9

    Defining Object Composition 2-11

    The Donut Diagram 2-13

    Guided Practice: Spot the Operations and Attributes 2-14Collaborating Objects 2-15

    Objects Interact Through Messages 2-16

    What Is a Class? 2-17

    How Do You Identify a Class? 2-18

    Comparing Classes and Objects 2-19

    What Is Encapsulation? 2-21

    What Is Inheritance? 2-22

    Contents

    ii i

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    4/419

    Using the “Is-a-Kind-of” Relationship 2-23

    What Is Polymorphism? 2-24

     Architecture Rules for Reuse 2-26

    Engineering for a Black Box Environment 2-27

    Order Entry UML Diagram 2-28

    Summary 2-29

    Practice 2: Overview 2-30Order Entry System Partial UML Class Model 2-33

    3 Basic Java Syntax and Coding Conventions

    Objectives 3-2

    Examining Toolkit Components 3-4

    Exploring Packages in J2SE/J2EE 3-5

    Documenting Using the J2SE 3-6

    Contents of a Java Source 3-7

    Establishing Naming Conventions 3-8

    More About Naming Conventions 3-10

    Defining a Class 3-12Rental Class: Example 3-13

    Creating Code Blocks 3-15

    Defining Java Methods 3-16

    Examples of a Method 3-17

    Declaring Variables 3-18

    Examples of Variables in the Context of a Method 3-19

    Rules for Creating Statements 3-20

    What Are JavaBeans? 3-21

    Managing Bean Properties 3-22

    Exposing Properties and Methods 3-23JavaBean Standards at Design Time 3-24

    Compiling and Running a Java Application 3-25

    The CLASSPATHVariable 3-26

    CLASSPATH: Example 3-27

    Summary 3-28

    Practice 3: Overview 3-29

    4 Exploring Primitive Data Types and Operators

    Objectives 4-2

    Reserved Keywords 4-4

    Variable Types 4-5Primitive Data Types 4-7

    What Are Variables? 4-9

    Declaring Variables 4-10

    Local Variables 4-11

    Defining Variable Names 4-12

    What Are Numeric Literals? 4-13

    What Are Nonnumeric Literals? 4-15

    iv

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    5/419

    Guided Practice: Declaring Variables 4-17

    What Are Operators? 4-19

    Categorizing Operators 4-20

    Using the Assignment Operator 4-21

    Working with Arithmetic Operators 4-22

    More on Arithmetic Operators 4-23

    Examining Conversions and Casts 4-24Incrementing and Decrementing Values 4-26

    Relational and Equality Operators 4-27

    Using the Conditional Operator (?:) 4-28

    Using Logical Operators 4-29

    Compound Assignment Operators 4-30

    Operator Precedence 4-31

    More on Operator Precedence 4-32

    Concatenating Strings 4-33

    Summary 4-34

    Practice 4: Overview 4-35

    5 Controlling Program Flow

    Objectives 5-2

    Categorizing Basic Flow Control Types 5-4

    Using Flow Control in Java 5-6

    Using the i f  Statement 5-7

    Nesting i f  Statements 5-8

    Guided Practice: Spot the Mistakes 5-9

    Defining the swi t ch Statement 5-10

    More About the swi t ch Statement 5-12

    Looping in Java 5-13Using the whi l e Loop 5-14

    Using the do…whi l e Loop 5-15

    Using the f or Loop 5-16

    More About the f or Loop 5-17

    Guided Practice: Spot the Mistakes 5-18

    The br eak Statement 5-19

    Summary 5-20

    Practice 5: Overview 5-21

    6 Building Applications with Oracle JDeveloper 10g

    Objectives 6-2What Is Oracle JDeveloper 10g? 6-3

    Exploring the JDeveloper Environment 6-4

    Examining Workspaces 6-5

    What Are Projects? 6-7

    Creating JDeveloper Items 6-8

    Creating an Application Workspace 6-9

    Specifying Project Details 6-10

    Selecting Additional Libraries 6-11

    v

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    6/419

     Adding a New J2SE 6-12

    Looking at the Directory Structure 6-13

    Exploring the Skeleton Java Application 6-14

    Finding Methods and Fields 6-15

    Supporting Code Development with Profiler and Code Coach 6-16

    Customizing JDeveloper 6-17

    Using the Help System 6-18Obtaining Help on a Topic 6-19

    Oracle JDeveloper 10g Debugger 6-20

    Setting Breakpoints 6-22

    Using the Debugger Windows 6-24

    Stepping Through a Program 6-25

    Watching Data and Variables 6-26

    Summary 6-27

    Practice 6: Overview 6-28

    7 Creating Classes and Objects

    Objectives 7-2Using Java Classes 7-4

    Comparing Classes and Objects 7-5

    Creating Objects 7-6

    Using the newOperator 7-7

    Comparing Primitives and Objects 7-8

    Using the nul l Reference 7-9

     Assigning References 7-10

    Declaring Instance Variables 7-11

     Accessing publ i c Instance Variables 7-12

    Defining Methods 7-13Calling a Method 7-14

    Specifying Method Arguments: Examples 7-15

    Returning a Value from a Method 7-16

    Calling Instance Methods 7-17

     Applying Encapsulation in Java 7-18

    Passing Primitives into Methods 7-19

    Passing Object References into Methods 7-20

    What Are Class Variables? 7-21

    Initializing Class Variables 7-22

    What Are Class Methods? 7-23

    Guided Practice: Class Methods or Instance Methods 7-24

    Examples in Java 7-25

    Creating Classes Using the Class Editor 7-26

    What Are Java Packages? 7-27

    Grouping Classes in a Package 7-28

    vi

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    7/419

    Setting the CLASSPATHwith Packages 7-29

     Access Modifiers 7-30

    Summary 7-32

    Practice 7: Overview 7-33

    8 Object Life Cycle and Inner Classes

    Objectives 8-2

    Overloading Methods 8-4

    Using the t hi s Reference 8-5

    Initializing Instance Variables 8-6

    What Are Constructors? 8-7

    Defining and Overloading Constructors 8-8

    Sharing Code Between Constructors 8-9

    f i nal Variables, Methods, and Classes 8-10

    Reclaiming Memory 8-11

    Using the f i nal i ze( ) Method 8-12

    What Are Inner Classes? 8-13

    Using Member Inner Class 8-14Using Local Inner Class 8-15

    Defining Anonymous Inner Classes 8-16

    Using the Cal endar Class 8-17

    Summary 8-18

    Practice 8: Overview 8-19

    9 Using Strings, String Buffer, Wrapper, and Text-Formatting Classes

    Objectives 9-2

    What Is a St r i ng? 9-3

    Creating a St r i ng 9-4

    Concatenating Strings 9-5

    Performing Operations on Strings 9-6

    Performing More Operations on Strings 9-7

    Comparing St r i ng Objects 9-8

    Producing Strings from Other Objects 9-9

    Producing Strings from Primitives 9-10

    Producing Primitives from Strings 9-11

    Wrapper Class Conversion Methods 9-12

    Changing the Contents of a String 9-13

    Formatting Classes 9-14

    Using the Si mpl eDat eFor mat Class 9-15Using the Mes sageFor mat Class 9-16

    Using Deci mal For mat 9-17

    Guided Practice 9-18

    Using Regular Expressions 9-20

    vii

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    8/419

     About Syst em. out . pr i nt l n 9-23

     About Out put St r eamand Pr i nt St r eam 9-24

    What Is Object Serialization? 9-25

    Serialization Streams, Interfaces, and Modifiers 9-28

    Summary 9-29

    Practice 9: Overview 9-30

    10 Reusing Code with Inheritance and Polymorphism

    Objectives 10-2

    Key Object-Oriented Components 10-3

    Example of Inheritance 10-4

    Specifying Inheritance in Java 10-5

    Defining Inheritance by Using Oracle JDeveloper 10g 10-6

    What Does a Subclass Object Look Like? 10-7

    Default Initialization 10-8

    The super Reference 10-9

    The super Reference Example 10-10

    Using Superclass Constructors 10-11Specifying Additional Methods 10-13

    Overriding Superclass Methods 10-15

    Invoking Superclass Methods 10-17

    Example of Polymorphism in Java 10-19

    Treating a Subclass as Its Superclass 10-20

    Browsing Superclass References by Using Oracle JDeveloper 10g 10-21

     Acme Video and Polymorphism 10-22

    Using Polymorphism for Acme Video 10-23

    Using the i nst anceof  Operator 10-25

    Limiting Methods and Classes with f i nal 10-26Ensuring Genuine Inheritance 10-27

    Summary 10-28

    11 Using Arrays and Collections

    Objectives 11-2

    What Is an Array? 11-3

    Creating an Array of Primitives 11-4

    Declaring an Array of Primitives 11-5

    Creating an Array Object for an Array of Primitives 11-6

    Initializing Array Elements 11-8

    Creating an Array of Obj ect References 11-9Initializing the Objects in the Array 11-10

    Using an Array of Obj ect References 11-11

     Arrays and Exceptions 11-12

    Multidimensional Arrays 11-13

    mai n( ) Revisited 11-14

    viii

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    9/419

    Working with Variable-Length Structures 11-15

    Modifying a Vector 11-16

     Accessing a Vector 11-17

    Java Collections Framework 11-18

    Collections Framework Components 11-20

    Using Ar r ayLi st and Hasht abl e 11-21

    Using I t er at or s 11-22Summary 11-23

    Practice 11: Overview 11-24

    12 Structuring Code by Using Abstract Classes and Interfaces

    Objectives 12-2

    Defining Abstract Classes 12-3

    Creating Abstract Classes 12-4

    What Are Abstract Methods? 12-5

    Defining Abstract Methods 12-7

    Defining and Using Interfaces 12-8

    Examples of Interfaces 12-9Creating Interfaces 12-10

    Implementing Interfaces 12-12

    Sort: A Real-World Example 12-13

    Overview of the Classes 12-14

    How the Sort Works 12-15

    The Sor t abl e Interface 12-16

    The Sor t Class 12-17

    The Movi e Class 12-18

    Using the Sort 12-19

    Using i nst anceof  with Interfaces 12-20Summary 12-21

    Practice 12: Overview 12-22

    13 Throwing and Catching Exceptions

    Objectives 13-2

    What Is an Exception? 13-3

    How Does Java Handle Exceptions? 13-4

     Advantages of Java Exceptions: Separating Error Handling Code 13-5

     Advantages of Java Exceptions: Passing Errors Up the Call Stack 13-7

     Advantages of Java Exceptions: Exceptions Cannot Be Ignored 13-8

    Checked Exceptions, Unchecked Exceptions, and Errors 13-9What to Do with an Exception 13-11

    Catching and Handling Exceptions 13-12

    Catching a Single Exception 13-13

    Catching Multiple Exceptions 13-14

    ix

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    10/419

    Cleaning Up with a f i nal l y Block 13-15

    Catching and Handling Exceptions: Guided Practice 13-16

     Allowing an Exception to Pass to the Calling Method 13-18

    Throwing Exceptions 13-19

    Creating Exceptions 13-20

    Catching an Exception and Throwing a Different Exception 13-21

    Summary 13-22Practice 13: Overview 13-23

    14 User Interface Design: Swing Basics Planning the Application Layout

    Objectives 14-2

    Running Java UI Applications 14-3

     AWT, Swing, and JFC 14-4

    Swing Features 14-6

    Lightweight or Heavyweight Components? 14-8

    Planning the UI Layout 14-9

    The Containment Hierarchy 14-10

    Top-Level Containers 14-12Intermediate Containers 14-14

     Atomic Components 14-15

    Layout Management Overview 14-16

    Border Layout 14-18

    GridBag Layout 14-19

    GridBag Constraints 14-20

    Using Layout Managers 14-22

    Combining Layout Managers 14-24

    Using Frames or Dialogs 14-25

    Using  J Panel Containers 14-27 Adding Borders to Components 14-29

    Using Internal Frames 14-30

    Swing Text Controls 14-32

     Adding Components with Oracle JDeveloper 10g 14-33

    Creating a Frame 14-34

     Adding Components 14-35

    Setting Pluggable Look and Feel 14-37

    Summary 14-39

    Practice 14: Overview 14-40

    15 Adding User Interface Components and Event HandlingObjectives 15-2

    Swing Components 15-3

    Swing Components in JDeveloper 15-5

    Invoking the UI Editor 15-7

    How to Add a Component to a Form 15-8

    Edit the Properties of a Component 15-9

    Code Generated by JDeveloper 15-10

    x

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    11/419

    Creating a Menu 15-12

    Using JDeveloper Menu Editor 15-13

    Practice 15-1: Overview 15-14

    UI for Java Application 15-15

    Java Event Handling Model 15-20

    Event Handling Code Basics 15-21

    Event Handling Process: Registration 15-22Event Handling Process: The Event Occurs 15-24

    Event Handling Process: Running the Event Handler 15-25

    Using Adapter Classes for Listeners 15-26

    Swing Model View Controller Architecture 15-27

    Basic Text Component Methods 15-30

    Basic  J Li st Component Methods 15-31

    What Events Can a Component Generate? 15-32

    How to Define an Event Handler in JDeveloper 15-33

    Default Event Handling Code Style Generated by JDeveloper 15-34

    Completing the Event Handler Method 15-35

    Summary 15-36

    Practice 15-2: Overview 15-37

    16 Using JDBC to Access the Database

    Objectives 16-2

    Java, J2EE, and Oracle 10g 16-3

    Connecting to a Database with Java 16-4

    What Is JDBC? 16-5

    Preparing the Environment 16-6

    Steps for Using JDBC to Execute SQL Statements 16-8

    Step 1: Registering the Driver 16-9Connecting to the Database 16-10

    Oracle JDBC Drivers: Thin Client Driver 16-11

    Oracle JDBC Drivers: OCI Client Drivers 16-12

    Choosing the Right Driver 16-13

    Step 2: Getting a Database Connection 16-14

     About JDBC URLs 16-15

    JDBC URLs with Oracle Drivers 16-16

    Step 3: Creating a Statement 16-17

    Using the Statement Interface 16-18

    Step 4a: Executing a Query 16-19

    The Resul t Set Object 16-20

    Step 4b: Submitting DML Statements 16-21

    Step 5: Processing the Query Results 16-23

    Step 6: Closing Connections 16-24

     A Basic Query Example 16-25

    xi

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    12/419

    Mapping Database Types to Java Types 16-26

    Handling an Unknown SQL Statement 16-28

    Handling Exceptions 16-29

    Managing Transactions 16-30

    The Pr epar edSt at ement Object 16-31

    How to Create a Pr epar edSt at ement 16-32

    How to Execute a Pr epar edSt at ement 16-33Maximize Database Access 16-34

    Connection Pooling 16-35

    Summary 16-38

    Practice 16: Overview 16-39

    17 Deploying Appl ications by Using Java Web Start

    Objectives 17-2

    What Is Java Web Start? 17-3

    Running a Web Start Application 17-4

     Advantages of Web Start 17-5

    Examining the JNLP File 17-6Deploying Applications with JDeveloper 17-7

    Creating the Deployment Profile File 17-8

    Saving the Deployment Profile 17-9

    Selecting Files to Deploy 17-10

    Making an Executable . j ar File 17-11

    Creating and Deploying the Archive File 17-12

    Using JDeveloper to Deploy an Application to Java Web Start 17-13

    Step 1: Generate Deployment Profiles and Archive Application 17-14

    Step 2a: Start OC4J 17-15

    Step 2b: Creating a Connection 17-16

    Step 3: Use Web Start Wizard to Create a JNLP File 17-17

    Step 4: Archive and Deploy the Application to the OC4J Server 17-18

    Summary 17-19

    Practice 17: Overview 17-20

     Appendix A: Practice Solu tions

     Appendix B: Java Language Quick-Reference Guide

     Appendix C: Order Ent ry Solut ion

    xi i

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    13/419

    Copyright © 2004, Oracle. All rights reserved.

    Using Arrays and Collections

    Schedule: Timing Topic

    60 minutes Lecture

    30 minutes Practice

    90 minutes Total

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    14/419

    11-2 Copyright © 2004, Oracle. All rights reserved.

    Objectives

     After completing this lesson, you should be able to do

    the following:• Describe how to create arrays of primit ives and

    objects

    • Process command-line variables

    • Work with vectors

    • Explore other Java collections such as

    Enumerators, Iterators, ArrayLists, andHashtables

    • Process command-line and system properties

    Lesson Aim

    This lesson shows how to use Java collection objects, introducing the Java array of primitive, array of Obj ect references and other collection classes such as Vectors,Hasht abl es, Properties, Enumer at or s and I t er at or s .

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    15/419

    11-3 Copyright © 2004, Oracle. All rights reserved.

    What Is an Array?

     An array is a collection of variables of the same type.

    • Each element can hold a single item.

    • Items can be primit ives or object references.

    • The length of the array is fixed when it is created.

    1

    2

    4

    8

    [0]

    [1]

    [2]

    [3]

     Action

    Comedy

    Drama

    [0]

    [1]

    [2]

     Arrays

    Arrays are useful when you want a group of objects that you can manipulate as a whole.

    For example, if you are writing a program to allow users to search for a movie, you would

     probably store the list of categories in an array.

    The slide shows an array of four integers and an array of three strings. The following slides

    show how to create and initialize the arrays. As you will soon see, an array in Java is an

    object.

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    16/419

    11-4 Copyright © 2004, Oracle. All rights reserved.

    Creating an Array of Primitives

    1. Declare the array:

    type is a primit ive, such as int and so on.

    2. Create the array object:

    3. Init ialize the array elements

    (optional).

    NullarrayName

    arrayName1

    2

    4

    0

    0

    0

    arrayName

    type[] arrayName;

    … or …

    type arrayName[];

    // Create array object syntax

    arrayName = new type[size];

    Creating an Array of Primitives

    1. Declaration: Create the variable that references the array.

    2. Creation: Create an array object of the required type and size, and store a reference

    to the array in the array variable.

    3. Initialization: Initialize the array elements to the values that you want. This is

    optional for an array of primitives, because the elements are initialized to default

    values when the array object is created. The following slides explain these three steps

    in detail.

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    17/419

    11-5 Copyright © 2004, Oracle. All rights reserved.

    Declaring an Array of Primitives

    • Create a variable to reference the array object:

    • When an array variable is declared:

     –  Its instance variable is initialized to null until the

    array object has been created

     –  Its method variable is unknown unt il the object is

    created

    int[] powers; // Example

    null powers

    Declaring an Array

    There are two ways to declare an array:

    Most Java programmers use the first style because it separates the variable type (in theexample, an array of i nt ) from the variable name, making the code clearer to read.

    When you declare an array variable, it refers to nul l initially, until you initialize the array by using new.

    Instructor Note

    Although an array is an object, there is no array class. Instead, for every primitive type or

    class, Java automatically provides an array class.

    Syntax Example

    type[] arrayname; int[] powers;

    type arrayname[]; int powers[];

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    18/419

    11-6 Copyright © 2004, Oracle. All rights reserved.

    Creating an Array Object for 

    an Array of Primitives

    • Create an array of the required length and assign

    it to the array variable:

     –  The array object is created by using the new

    operator.

    • The contents of an array of primitives are

    initialized automatically.

    int[] powers; // Declare array variable

     powers = new int[4]; //Create array object

     powers 0

    0

    0

    0

    Creating an Array Object

    If you are using the new operator, you must specify the array size inside the brackets. The

    size must be an integer, but does not have to be a constant number; it could be an

    expression that is evaluated at run time.

    After the array object has been created, its length is fixed for the lifetime of the array.

    Default Initialization of Array Elements

    All elements in a new array of primitives are initialized automatically with default values,as follows:

    •   char elements are set to ' \ u0000' .•   byt e, shor t , i nt , and l ong elements are set to 0.•   bool ean elements are set to f al se.•   f l oat and doubl e elements are set to 0. 0.

    Note: ' \ u0000' is Unicode 0000. Java uses the Unicode character set.

    Examples of Valid Array Creation

    Example 1

    f i nal i nt SI ZE = 4;

    i nt [ ] powers = new i nt [ SI ZE] ; / / SI ZE i s a const ant

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    19/419

    Creating an Array Object (continued)

    Examples of Valid Array Creation (continued)

    Example 2

    i nt [ ] examMarks;i nt num = askUserHowManySt udent s( ) ; / / set t he val ue of num

    examMar ks = new i nt [ num] ; / / ar r ay i s a f i xed si ze

    Examples of Invalid Array Creation

    Example 1i nt powers[ 4] ; / / I nval i d synt ax: you can’ t set t he si ze of 

    / / t he ar r ay i n t he decl arat i on st at ement .

    Example 2

    i nt num;

    i nt [ ] examMar ks = new i nt [ num] ; / / Compi l at i on er r or : num has/ / not been i ni t i al i zed

    Instructor Note

    Arrays can be created and initialized at the same time; the syntax for doing this is coveredin the following slide.

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    20/419

    11-8 Copyright © 2004, Oracle. All rights reserved.

    Init ializing Array Elements

    •  Assign values to individual elements:

    • Create and initialize arrays at

    the same time:

    int[] primes = {2, 3, 5, 7};

    type[] arrayName = {valueList};

     primes [0][1]

    [2]

    23

    5

    7 [3]

    arrayName[index] = value;

     powers[0] = 1; powers

    [0]

    [1]

    [2]

    1

    0

    0

    0 [3]

    Initializing Array Elements

    First Method: Assign a Value to Each Array Element

    To refer to an element in an array, use an index in brackets ([ ] ) as shown in the slide.Array elements are numbered from 0 to n- 1, where n is the number of elements in thearray. In other words, the index of the first element in an array is 0, not 1.

    Second Method: Use Array Initializers

    As shown in the slide, there is a shorthand technique for creating and initializing an arrayof primitives. Here, there is no need to use the newoperator, and the length of the array is

    set automatically. Note the use of the braces, and remember the semicolon at the end.

    Array initializers are very useful for creating lookup tables, as in the following example:

    i nt [ ] daysI nMont h = {31, 28, 31, 30, 31, 30,31, 31, 30, 31, 30, 31};

    This method is useful only if the value of each element is known when the array is created.

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    21/419

    11-9 Copyright © 2004, Oracle. All rights reserved.

    Creating an Array of Object References

    1. Declare the array:

    2. Create the array object:

    3. Initialize the objects in the array.

    nullarrVar

    null

    null

    null

    arrVar

     Action

    Comedy

    Drama

    arrVar

    ClassName[] arrVar;

    … or …

    ClassName arrVar[];

    // Create array object syntax

    arrVar = new ClassName[size];

    Creating an Array of Objects

    The steps for creating an array of object references are the same as for arrays of primitives,

    with one exception: You must initialize the elements in the array, because this is not done

    automatically.

    1. Declaration: The syntax is the same as for arrays of primitive objects. For example,St r i ng[ ] cat egor i es;declares a variable that can point to an array of St r i ng. If the variable is theinstance variable, the variable is set to nul l initially.

    2. Creation: The syntax is the same as for arrays of primitive objects. For example,cat egor i es = new St r i ng[ 3] ;creates an array object of the correct type (St r i ng) and a size of 3. Initially, all ofthe elements are set to nul l .You can declare and create an array in the same statement. For example, St r i ng[ ]cat egor i es = new St r i ng[ 3] ;

    3. Initialization: Initialize the array elements to the values that you want. This isdescribed in the next slide.

    Instructor Note

    It is important to emphasize that step 2 creates an array of three nul l s and that this is notthe same as an array of three empty strings.

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    22/419

    11-10 Copyright © 2004, Oracle. All rights reserved.

    Init ializing the Objects in the Array

    •  Assign a value to each array element:

    • Create and initialize the array at the same time:

    String[] categories =

    {"Action", "Comedy", "Drama"};

    // Create an array of four empty Strings

    String[] arr = new String[4];

    for (int i = 0; i < arr.length; i++) {

    arr[i] = new String();

    }

    Initializing the Objects in an Array

    As with arrays of primitives, there are two ways of initializing an array of object

    references. You can initialize the array by assigning a value to each array element or by

    initializing the array when you create it.

    The length Property

    Every array has a l engt h attribute that contains the number of elements in the array. Byusing l engt h, you can avoid the need to hardcode or store the size of an array in yourcode. Because the index of the first element in an array is 0, the index of its last element is

    l engt h – 1.

    The example in the slide uses l engt h to loop through all the elements of an array to

    create an array of empty strings.

    Incidentally, the Syst emclass provides a useful method for copying all or part of an arrayto another array. For more information, refer to Syst em. ar r aycopy( ) in the Java

    Development Kit (JDK) documentation.

    Instructor Note

    It is a good practice to initialize an array of object references immediately after it is

    created. That way you can be sure that the rest of your code can safely reference thecontents of the array. If you do not know the value of the array elements at creation time,

    you must initialize each element to an empty object, like the example in the slide does.

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    23/419

    11-11 Copyright © 2004, Oracle. All rights reserved.

    Using an Array of Object References

    •  Any element can be assigned to an object of the

    correct type:

    • Each element can be treated as an individual

    object:

    •  An array element can be passed to any method;

    array elements are passed by reference.

    System.out.println

    ("Length is " + categories[2].length());

    String category = categories[0];

    Passing Arrays to Methods

    Because arrays behave like objects when an array is passed into a method, it is passed by

    reference like any other object. Therefore, if the method changes the contents of the array,

    these changes operate on the original array, not a copy.

    Instructor Note

    The second example calls the method St r i ng. l engt h( ) to determine the length of oneof the strings in the array. Assuming that the array has been initialized to {"Act i on" ,"Comedy" , "Dr ama" } as in the previous slide, this code fragment prints the following

    line:

    Lengt h i s 5

    (That is the length of the string "Dr ama" .)

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    24/419

    11-12 Copyright © 2004, Oracle. All rights reserved.

     Arrays and Exceptions

    •  ArrayIndexOutOfBoundsException occurs

    when an array index is invalid:

    •  NullPointerException occurs when you try to

    access an element that has not been initialized:

     Movie[] movieList = new Movie[3];

    // The following will throw NullPointerException

    String director = movieList[0].getDirector();

    String[] list = new String[4];

    //The following throws ArrayIndexOutOfBoundsException

    System.out.println(list[4]);

     Arrays and Except ions

    The slide shows the exceptions, or errors, that occur when you try to perform an invalid

    operation on an array. Exceptions are covered in more detail in the lesson titled “Throwing

    and Catching Exceptions”; these are included in this slide because you are likely to see

    these errors if your code attempts to perform one of the operations that is described in the

    slide.

    If you try to access an invalid array index, then your program will crash with the error“Ar r ayI ndexOut Of BoundsExcept i on”.

    If you try to access an array element that has not been initialized, your program will crashwith the error “Nul l Poi nter Except i on”.

    Instructor Note

    In the first example, the code is trying to access an element beyond the bounds of the array.The array length was fixed to 4 when the array was created.

    In the second example, the code is trying to access a method of one of the elements of thearray, but the array has not been initialized; at this point, it is an array of three nul l s .

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    25/419

    11-13 Copyright © 2004, Oracle. All rights reserved.

    Multidimensional Arrays

    Java supports arrays of arrays:

    type[][] arrayname = new type[n1][n2];

    int[][] mdarr = new int[4][2];

     mdarr[0][0] = 1;

     mdarr[0][1] = 7;

    [0][1]

    [2]

    [3]

    1 7

    0 0

    0 0

    0 0

     mdarr

    [0][0] [0][1]

    Multidimensional Arrays

    Java supports multidimensional arrays; that is arrays of arrays:i nt [ ] [ ] t ax = new i nt [ 5] [ 4] ;

    This declares and creates a two-dimensional matrix; the matrix contains five rows, each of

    which contains four columns. Individual elements can be accessed as follows:t ax[rowIndex ] [ colIndex ] = value;

    Advanced Topic: Nonsquare Multidimensional Arrays

    The following example creates a multidimensional array with 10 rows, but the number of

    columns in each row is different: the first row has one element, the second row has two

    elements, and so on.i nt [ ] [ ] a = new i nt [ 10] [ ] ;f or ( i nt i = 0; i < a. l engt h; i ++) {

    a[ i ] = new i nt [ i + 1] ;}

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    26/419

    11-14 Copyright © 2004, Oracle. All rights reserved.

     main() Revisited

    •  main() has a single parameter, args.

    • args is an array of Strings that holds command-line parameters:

     public class SayHello {

     public static void main(String[] args) {

    if (args.length != 2)System.out.println("Specify 2 arguments");

    else

    System.out.println(args[0]+" "+args[1]);

    } …

    C:\> java SayHello Hello World 

    Passing Command-Line Parameters to main()

    A reference to an array can be passed to any method. A good example is the mai n( )

    method that is used in Java applications. When you start a Java application, as opposed to aJava applet, the system locates and calls the mai n( ) method for that class.

    The mai n( ) method has a single parameter, which is a reference to an array of St r i ngobjects. Each St r i ng object holds a command-line parameter; the first element in the

    array contains the first command-line parameter, not the name of the program as in C and

    C++.

    Command-Line Parameters Are Always Converted to Strings

    It is important to note that command-line parameters are always represented by St r i ngobjects. Inside the mai n( ) method, you may need to convert a parameter to a primitive

    type. For example, if one of the command-line parameters represents a number, you mayneed to convert it into an i nt to perform some arithmetic with it.

    Specifying Command-Line Parameters in JDeveloper

    JDeveloper has a dialog box that you can use to specify command-line parameters for a

    Java application. When you run the application from the JDeveloper environment,JDeveloper passes the parameters into the mai n( ) method, as usual.

    To specify command-line parameters in JDeveloper, select the Project > Project Properties

    item from the menu bar, and click the Run/Debug tab. This tab has a field where you can

    define command-line arameters.

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    27/419

    11-15 Copyright © 2004, Oracle. All rights reserved.

    Working with Variable-Length Structures

    The Vector class implements a “ resizable” array of

    any type of object:• Creating an empty vector:

    • Creating a vector with an initial size:

     Vector members = new Vector();

    // Create a vector with 10 elements. The vector //can be expanded later.

     Vector members = new Vector(10);

    Vectors

    The Vect or class, belonging to the j ava. ut i l  package, provides a resizeable

    collection of objects. Remember that Java arrays are fixed in size, so a vector is useful

    when you do not know how large an array will be at the time when you create the array.

    For example, you may get a list of names from a server and want to store the names in a

    local array. Before you fetch the data from the server, you have no idea how large the list

    is.

    You cannot create a vector of i nt , f l oat , or any other primitive. Instead, you must use

    the wrapper classes, which were discussed in the lesson titled “Using Strings,St r i ngBuf f er , Wrapper and Text-Formatting Classes,” and create a vector ofI nt eger , Fl oat , and so on.

    The Vect or class provides methods to modify and access the vector. The following slides

    show some of these methods; the JDK 1.4 online documentation provides complete

    information.

    Instructor Note

    To use vectors, you must import the Vect or class:

    i mpor t j ava. ut i l . Vect or ;

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    28/419

    11-16 Copyright © 2004, Oracle. All rights reserved.

    Modifying a Vector 

    •  Add an element to the end of the vector:

    •  Add an element at a specific position:

    • Remove the element at a specific index:

    String name = MyMovie.getNextName();

     members.addElement(name);

    // Remove the first element

     members.removeElementAt(0);

    // Insert a string at the beginning

     members.insertElementAt(name, 0);

    Modifying a Vector 

    When you add an element to a vector, the vector is automatically expanded by one element.

    When you remove an element from a vector, the size of the vector decreases automatically.

    When you insert an element at a specific position, all elements after that position increase

    their indexes by 1.

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    29/419

    11-17 Copyright © 2004, Oracle. All rights reserved.

     Accessing a Vector 

    • Get the first element:

    • Get an element at a specific position:

    • Find an object in a vector:

    • Get the size of a vector:

    String s = (String)members.firstElement();

    int size = members.size();

    String s = (String)members.elementAt(2);

    int position = members.indexOf(name);

    Vector Indexing

    The index of the first element of a vector is 0.

     Note that a vector always contains objects. It can contain objects of different types. When

    you get an element from a vector, you must cast it to the type of object that you added to

    the vector.

    Example of a Vector Containing Different Objects

    The Vect or . addEl ement ( ) method accepts an Obj ect as its parameter type. By

    applying the principle of object reference substitution (subclass object plug-compatibilitywith its superclass), the parameter can be any subclass of the j ava. l ang. TheObj ect class, which includes just about every object that you can create. Here is a simpleexample, assuming that you have a class called Member :

    Vect or v = new Vect or ( ) ;v. addEl ement ( new Member ( ) ) ;v. addEl ement ( "pat " ) ;v. addEl ement ( new I nt eger ( 10) ) ;

    You must be sure of the type of object that you are getting returned from methods such asVect or el ement At ( ) or f i r st El ement ( ) . You can use the i nst anceof 

    operator to determine the object type that is returned by these methods.

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    30/419

    11-18 Copyright © 2004, Oracle. All rights reserved.

    Java Collections Framework

    Java Collections Framework is an API architecture for

    managing a group of objects that can be manipulatedindependently of their internal implementation. It is:

    • Found in the java.util package

    • Defined by six core interfaces and some

    implementation classes: –  Collection interface: Generic group of elements

     –  Set interface: Group of unique elements

     –  List interface: Ordered group of elements –  Map interface: Group of unique keys and their

    values –  SortedSet and SortedMap for a sorted Set and Map

    Java Collections Framework

    Java Collections Framework is an API architecture for managing a collection of objects

    that can be manipulated independently of their internal implementation. The framework is

    a unified architecture for representing and manipulating collections. All collections

    frameworks contain three things: Interfaces, Implementations, and Algorithms

    The framework is built around six core interfaces and many implementation classes that arefound in the j ava. ut i l  package. The Col l ect i on interface is inherited by the Setand Li st interfaces. The Sor t edSet is a subclass of Set , and Sor t edMap is a

    subclass of Map.

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    31/419

    Java Collections Framework (continued)

    The Col l ect i on interface is an abstraction representing a group of objects called

    elements.

    The Set interface models mathematical set abstraction. It is a collection that cannotcontain duplicate elements. The implementation classes are HashSet and Tr eeSet .

    The Li st interface represents an ordered collection (or sequence) of elements, including

    duplicates. Lists provide control over where each element is inserted. Elements can beaccessed by their integer index (position). Implementing classes are Ar r ayLi st andLi nkedLi st . Lists are similar to vectors.

    The Map interface represents an object that maps one or more keys to their values. Maps do

    not contain duplicate keys, and each key maps to a single value. Implementing classes areHashMap and Tr eeMap. These are similar to a Hasht abl e.

    Sorted collections are provided through the Sor t edSet and Sor t edMap interfaces,which are sorted versions of Set and Map, respectively.

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    32/419

    11-20 Copyright © 2004, Oracle. All rights reserved.

    Collections Framework Components

    Collections Framework is a set of interfaces and

    classes used to store and manipulate groups of dataas a single unit.

    • Core Interfaces are the interfaces used to

    manipulate collections, and to pass them from one

    method to another.

    • Implementations are the actual data objects used

    to store collections, which implement the core

    collection interface.

    •  Algorithms are pieces of reusable functionality

    provided by the JDK.

    Java Collections Framework Components

    The design of programs often requires handling of groups of objects. This collection

    framework offers a set of standard utility classes to manage the collection of these objects.

    The framework is made up of three main components (listed on the previous page):

    • Core Interfaces: These allow collections to be manipulated, independent of their 

    implementation. These interfaces describe a common set of functionality, displayed

     by collections, and enhance data exchange between collections. In object-oriented

    languages, these interfaces, generally, are contained within a hierarchy.

    • Implementations: A small set of implementations exists as concrete implementationsof the core interfaces, which provide a data structure that a program can use. In a

    sense, these are reusable data structures. The implementations come in three flavors:

    general-purpose, wrapper, and convienience.

    • Algorithms: Methods that perform useful computations, such as searching and 

    sorting, on objects that implement collection interfaces. These algorithms are said to

     be polymorphic because the same method can be used on many different

    implementations of the appropriate collections interface. In essence, algorithms are

    reusable functionality.

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    33/419

    11-21 Copyright © 2004, Oracle. All rights reserved.

    Using ArrayList and Hashtable

    The ArrayList class:

    • Is a resizable implementation of the List interface

    •  Allows manipulation of the array size

    • Has capacity that grows as elements are added to

    the list

    The Hashtable class:

    • Is a legacy class similar to Map implementations

    • Is used to store arbitrary objects that are indexedby another arbitrary object

    • Is commonly used with String as the key to store

    objects as values

     ArrayList

    The Ar r ayLi st is a resizable-array implementation of the Li st interface. It implementsall optional list operations, and permits all elements, including nul l . In addition toimplementing the Li st interface, this class provides methods to manipulate the size of the

    array that is used internally to store the list.

    Hashtable

    The j ava. ut i l . Hasht abl e class provides a table of keys, where each key is hashed

    to an associated value object. The key and value can be any Java object. Here is an

    example of using the Hasht abl e to store String objects on information about a book.i mport j ava. ut i l . Hasht abl e;

    publ i c cl ass Hasht abl eDemo {

    publ i c st at i c voi d mai n ( St r i ng args[ ] ) {

    Hasht abl e ht = new Hasht abl e( ) ;

    ht . put ( " t i t l e", "Beyond Fr eedom and Di gi ni t y") ;

    ht . put ( "aut hor " , "B. F. Ski nner " ) ;

    ht . put ( "year " , "1971" ) ;

    Syst em. out . pr i nt l n( ht ) ;

    Syst em. out . pr i nt l n( "Year : " + ht . get ( "year " ) ) ;}

    }

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    34/419

    11-22 Copyright © 2004, Oracle. All rights reserved.

    Using Iterators

    The Iterator interface, which is part of Java

    Collection Framework, can be used to process a seriesof Objects. The java.util.Iterator interface:

    • Implements an object-oriented approach for

    accessing elements in a collection

    • Replaces the java.util.Enumeration approach

    • Contains the following methods:

     –  hasNext() returns true if more elements exist.

     –  next() returns the next Object, if any.

     –  remove() removes the last element returned.

     Another Type of Col lect ion

    Collections differ from arrays in that the members of a collection are not directly accessibleusing indices, as you would with arrays. When using an Enumer at i on or an I t er at or

    you can only move the current item pointer to the first or next element of a collection. TheEnumer at i on was part of the standard Java API, and the I t er at or was added withJava Collection Framework API. An I t er at or supports removal of an object from thecollection, whereas an Enumer at i on can only traverse the collection.

    The following example creates a Vect or containing several St r i ng elements, and then

    calls the i t er at or ( ) method to return an I t er at or object. The loop uses thenext ( ) method of the I t er at or is to get elements and display their string value in

    uppercase.

    When hasNext ( ) is f al se the loop terminates.i mpor t j ava. ut i l . Vect or ;i mport j ava. ut i l . I t erat or ;:Vect or v = new Vect or ( ) ;v. addEl ement ( " J azz" ) ;v. addEl ement ( "Cl assi cal " ) ;

    v. addEl ement ( "Rock ' n Rol l " ) ;f or ( I t er at or e = v.iterator(); e.hasNext(); ) {St r i ng s = ( St r i ng) e.next();Syst em. out . pr i nt l n( s. t oUpperCase( ) ) ;

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    35/419

    11-23 Copyright © 2004, Oracle. All rights reserved.

    Summary

    In this lesson, you should have learned how to:

    • Create Java arrays of primit ives

    • Create arrays of object references

    • Init ialize arrays of primitives or object references

    • Process command-line arguments in the main()

    method

    • Use the Vector object to implement resizable

    arrays• Use ArrayList and Hashtable classes

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    36/419

    11-24 Copyright © 2004, Oracle. All rights reserved.

    Practice 11: Overview

    This practice covers:

    • Modifying the DataMan class –  Create an array to hold the Customer, Company, and

    Individual objects.

     –   Add a method to ensure that the array is

    successfully created and initialized.

     –   Add a method to find a customer by an ID value.

    Practice 11: Overview

    Note: If you have successfully completed the previous practice, then continue using the

    same directory and files. If the compilation from the previous practice was unsuccessfuland you want to move on to this practice, then change to the l es10 directory, load theOr der Ent r yWorkspaceLes10 workspace, and continue with this practice.

    Viewing the model: To view the course application model up to this practice, load theOr der Ent r yWorkspaceLes10 workspace. In the Applications – Navigator node,expand the Or derEnt r yWorkspaceLes10 – Or derEnt r yPr oj ect Les10 -

    Appl i cat i on Sour ces – oe, and double- click on UML Cl ass Di agr am1entry. This diagram displays all the classes created to this point in the course.

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    37/419

    Practice 11: Using Arrays and Collections

    Goal

    The goal of this practice is to gain experience with Java array objects, and work withcollection classes such as the j ava. ut i l . Vect or class. You also work with command-line arguments.

    Note: If you have successfully completed the previous practice, then continue using the

    same directory and files. If the compilation from the previous practice was unsuccessfuland you want to move on to this practice, then change to the l es10 directory, load the

    Or der Ent r yWorkspaceLes10 workspace, and continue with this practice.

    Your Assignment

    Continue to use JDeveloper to build on the application classes from the previous practices.You will enhance the Dat aMan class to construct an array of Cust omer objects, andthen provide a method to find and return a Cust omer object for a given ID.

    The Order class is modified to contain a vector of order items, requiring a method to additems into the vector, and (optionally) another method to remove the items.

    Modify DataMan to Keep the Customer Objects in an Array

    1. Modify the Dat aMan class to build an array of customers.a. Define a private static array of Cust omer objects named cust omer s. b. Initialize the array to a nul l reference.

    2. Create a public static void method called bui l dCust omer s( ) to populate thearray of customers. The array must hold six objects by using the four Cust omerobjects, the Company object and the I ndi vi dual object that you have alreadycreated.

    a. In the body of the method, first test whether the cust omer s variable is notnul l , and if so, then return from the method without doing anything because anon-null reference indicates that the cust omer s array has been initialized. Ifcust omer s is nul l , then you must create the array object to hold the sixcustomer objects that are already created.

     b. Now move (cut and paste) the definitions of the four existing Cust omerobjects, the Company, and the I ndi vi dual into the body of this method,after creating the array object. Then, delete the st at i c keyword and classname or type before each cust omer variable name. Modify each variableto be the name of the array variable followed by brackets enclosing an arrayelement number. Remember, array elements start with a zero base.For example replace:

    st at i c Cust omer cust omer 1 = new Cust omer ( …) ;

    with: cust omer s[ 0] = new Cust omer ( …) ;The example here assigns the customer object to the first element in the array.Repeat this for each cust omer object references in the code.

    c. Create a static block that invokes the bui l dCust omer s( ) method to createand initialize the array of customer objects, when the Dat aMan class is loaded.Place the block at the end of the Dat aMan class. (Static blocks in the classdefinition are sometimes called class constructors.)

    st at i c

    {bui l dCust omers( ) ;}

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    38/419

    Practice 11: Using Arrays and Collections (continued)

    d. Save and compile the Dat aMan class. What other classes are compiled?Explain the results. (Only fix errors that are related to the Dat aMan class, ifany. Any errors pertaining to Or der Ent r y class will be fixed after doing the

    next set of questions).

    Hint: Look in the Messages and Compiler tabs of the Log Window.

    Modify DataMan to Find a Customer by ID

    3. Create a public static method called f i ndCust omerByI d( i nt cust I d) , where

    the argument represents the ID of the Cust omer object to be found. If found, thenreturn the object reference for the matching Cust omer , otherwise return a nul l

    reference value.

    a. Why is the customer array guaranteed to be initialized when thef i ndCust omer ByI d( ) method is called? Thus, you can write code

    assuming that the array is populated. b. Write a loop to scan through the cust omer s array, obtaining each customer

    object reference to compare the cust I d parameter value with the return valuefrom the get I d( ) method of each customer. If there is a match, then return

    the customer object reference; otherwise, return a nul l .c. Save and compile your Dat aMan class, only fixing the syntax errors that are

    reported for the Dat aMan class.4. You now fix the syntax errors in the Or der Ent r y class as a result of the changes

    made to Dat aMan. The modifications that you make to Or derEnt r y. j ava fixthe syntax errors, and test the code that is added to the Dat aMan class.

    a. In the Code Editor, locate and modify each line that directly refers to theDat aMan. cust omer variables that previously existed.

    Hint: You can quickly navigate to the error lines by double-clicking the errormessage line in the Compi l er tab of the Log Window.Replace each occurrence of the Dat aMan. cust omer text with a methodcall to: Dat aMan. f i ndCust omer ByI d( n) . For example, replace:Syst em. out . pr i nt l n(DataMan.customer1. t oSt r i ng( ) ) ;

    withSyst em. out . pr i nt l n(DataMan.findCustomerById(1). t oSt r i ng( ) ) ;

     b. Save, compile, and run the Or derEnt r y. j ava file to test your changes.

    Optional Extra Credit

    Modify the Order Class to Hold a Vector of OrderItem Objects

    Currently, the Or der class has hardcoded creation of two Or der I t emobjects as instancevariables, and the details of each Or der I t emobject is set in the get Or der Tot al ( )method. This is impractical for the intended behavior of the Or der class. You must nowreplace the two Or der I t emvariables with a Vect or that will contain the Or der I t emobjects. Therefore, you must create methods to add and remove Or der I t emobjects to

    and from the vector.

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    39/419

    Practice 11: Using Arrays and Collections (continued)

    Modify the Order Class to Hold a Vector of OrderItem Objects (continued)

    5. In the Or der class, define a Vect or of order items, and replace the Or der I t eminstance variables, removing code dependent on the original Or der I t eminstance

    variables.

    a. Add a statement at the beginning of your class, after the package statement, toimport the j ava. ut i l . Vect or class.

     b. Declare a new instance variable called i t ems as a Vect or object reference.

    Also remove, or comment out, the declarations of the two instance variablescalled i t em1 and i t em2, and the code that is using these variables.Hint: The following methods directly use the i t em1 and i t em2 variables:get Or der Tot al ( ) , showOr der ( ) .

    c. In the Or der no-arg constructor, add a line to create the item vector, as

    follows:i t ems = new Vect or ( 10) ;

    d. Compile and save your changes to the Or der class.

    Modify OrderItem to Handle Product Information

    6. Before you create the method to add an Or der I t emobject to the i t ems vector,you must first modify the Or der I t emclass to hold information about the product being ordered. Each Or der I t emobject represents an order line item. Each

    order line item contains information about a product that is ordered, its price, and 

    quantity that is ordered.a. Edit the Or der I t emclass and add a new instance variable called pr oduct .

    Declare the variable as a pr i vat e i nt , and generate or write theget Pr oduct ( ) method and set Pr oduct ( ) methods. Modify thet oSt r i ng( ) method to add the pr oduct value between the l i neNbr andquant i t y.

     b. Create an Or der I t emconstructor to initialize the object by using values thatare supplied from the following two arguments: i nt pr oduct I d anddoubl e i t emPr i ce.Initialize the item quant i t y variable to 1.Note: The Or der I t emclass will not provide a no-arg constructor.

    c. Save and compile the Or der I t emclass.

    Modify Order to Add Products into the OrderItem Vector

    7. In the Or der class, create a new publ i c voi d method calledaddOr der I t em( ) that accepts one argument: an integer called product ,

    representing an ID of the product being ordered. This method must perform the

    following tasks:a. Search the i t ems vector for an Or der I t emcontaining the supplied product.

    To do this, create a loop to get each Or der I t emelement from the i t ems

    vector.

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    40/419

    Practice 11: Using Arrays and Collections (continued)

    Hint: Use the si ze( ) method of the Vector object to determine the number ofelements in the vector. Use the get Pr oduct ( ) method of the Or der I t em

    class to compare the product value with the existing product value in the order

    item.If the product, with the specified ID, is found in an Or der I t emelements fromthe vector, then increment the quantity by using the set Quant i t y( ) method.If the specified product does not exist in any Or der I t emobject in the vector,

    then create a new Or der I t emobject by using the constructor that will acceptthe product, and a price. Then add the new Or der I t emobject into the vector.

    Note: Because line item numbers are set relative to their order, set the linenumber for the Or der I t em, by using the set Li neNbr ( ) method, after anitem is added to the vector. The line number is set using the si ze( ) of the

    vector, because the elements are added to the end of the vector. For now,

    assume that all products have a price of $5.00. b. The or der Tot al value will now be calculated as each product is added to the

    order. Thus, you must also add the price of each product to or der Tot al .Hint: Use the get Uni t Pr i ce( ) method from the Or der I t emclass.Because the or der Tot al is now updated as each product is added to theorder, the get Or der Tot al ( ) method can simply return the or der Tot al

    value.

    Note: This may already be done due to previous changes to the method.c. Modify the showOr der ( ) method to use an Enumeration technique to loop

    through the i t ems vector to display each Or der I t emobject by calling thet oSt r i ng( ) method.Hint: Import j ava. ut i l . Enumer at i on, and use the Vectorel ement s( ) method to create an Enumeration. See your course notes for an

    example, or ask your instructor for guidance.d. Save and compile the Or der class, and remove any syntax errors.e. Test your changes to the Or der I t emand Or der classes by modifying the

    Or der Ent r y class to add products 101, 102 to the first order object.For example, before the call to showOr der ( ) , enter the bold lines shown:

    order . set Cust omer ( Dat aMan. f i ndCust omerByI d( 5) ) ;order.addOrderItem(101);

    order.addOrderItem(102);

    order.addOrderItem(101);

    order . showOr der ( ) ;f. Compile (eliminating syntax errors first), save and run Or derEnt r y. j ava.

    Confirm that your results are accurate. For example, check whether the order

    total is reported as $15.

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    41/419

    Copyright © 2004, Oracle. All rights reserved.

    Structuring Code by Using

     Abstract Classes and Interfaces

    Schedule: Timing Topic

    40 minutes Lecture

    30 minutes Practice

    70 minutes Total

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    42/419Oracle10g: Java Programming 12-2

    12-2 Copyright © 2004, Oracle. All rights reserved.

    Objectives

     After completing this lesson, you should be able to dothe following:

    • Define abstract classes

    • Define abstract methods

    • Define interfaces

    • Implement interfaces

    Lesson Aim

    This lesson shows how abstract classes and abstract methods can be defined and used in

    Java. The lesson also introduces interfaces, and shows how they can be used to specify a set

    of methods that interested classes can implement if they want to. You learn how to use

    interfaces as an effective alternative to multiple inheritance.

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    43/419Oracle10g: Java Programming 12-3

    12-3 Copyright © 2004, Oracle. All rights reserved.

    Defining Abstract Classes

    •  An abstract class cannot be instantiated.•  Abstract methods must be implemented by

    subclasses.

    • Interfaces support mult iple inheritance.

     Abstract

    superclass

    Concretesubclasses

    InventoryItem 

     Movie VCR 

     Abstract Classes

    In Java, you can define classes that are high-level abstractions of real-world objects. Usingthese high-level classes gives the designer a vote in what subclasses look like and evenwhich methods are mandatory in the subclass.

    An abstract class is simply a class that cannot be instantiated; only its nonabstract subclassesmay be instantiated. For example, an I nvent or yI t emdoes not contain sufficient detail to provide anything meaningful to the business. It must either be a movie or a VCR. AnI nvent oryI t emdoes, however, serve as a collection of data and behaviors that arecommon to all items that are available for rent.

    Abstract Methods

    Abstract methods go a step beyond standard inheritance. An abstract method is defined onlywithin an abstract class, and must be implemented by a subclass. The class designer can usethis technique to decide exactly what behaviors a subclass must be able to perform. Thedesigner of the abstract class cannot determine how the behaviors will be implemented, onlythat they will be implemented.

    Interfaces

    An interface is the specification of a set of methods, which is similar to an abstract class. Inaddition to what an abstract class offers, an interface can effectively provide multipleinheritance. A class can implement an unlimited number of interfaces but can only extendone superclass.

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    44/419Oracle10g: Java Programming 12-4

    12-4 Copyright © 2004, Oracle. All rights reserved.

    Creating Abstract Classes

    Use the abstract keyword to declare a class asabstract.

     public abstract class InventoryItem {

     private float price;

     public boolean isRentable()…

    }

     public class Movie

    extends InventoryItem {

     private String title;

     public int getLength()…

     public class Vcr

    extends InventoryItem {

     private int serialNbr;

     public void setTimer()…

    Creating Abstract Classes

    Java provides the abst r act keyword, which indicates that a class is abstract. For example,the I nvent or yI t emclass in the slide has been declared as abstract:

    publ i c abstract cl ass I nvent or yI t em {…

    }

    I nvent oryI t emis declared abstract because it does not possess enough intelligence or

    detail to represent a complete and stand-alone object. The user must not be allowed to create

    I nvent oryI t emobjects, because I nvent or yI t emis only a partial class. TheI nvent oryI t emclass exists only so that it can be extended by more specializedsubclasses, such as Movi e and Vcr .

    What Happens If You Try to Instantiate an Abstract Class?

    If you try to create an I nvent oryI t emobject anywhere in the program, then the compiler

    flags an error:I nvent oryI t em i = new I nvent oryI t em ( …) ; / / Compi l er er r or

    The user can only create objects of the concrete subclasses:Movi e m = new Movi e( …) ; / / Thi s i s f i ne

    Vcr v = new Vcr ( …) ; / / Thi s i s f i ne t oo

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    45/419Oracle10g: Java Programming 12-5

    12-5 Copyright © 2004, Oracle. All rights reserved.

    What Are Abstract Methods?

    •  An abstract method: –  Is an implementation placeholder 

     –  Is part of an abstract class

     –  Must be overridden by a concrete subclass

    • Each concrete subclass can implement the

    method differently.

    The Need for Abstract Methods

    When you design an inheritance hierarchy, there will probably be some operations that all

    classes perform, each in its own way. For example, in a video rental business, the vendor

    must know whether each item is rentable or not. Each type of item, however, determines

    whether the item is rentable in a specific way.

    To represent this concept in Java, the common “is this item rentable” method is defined inthe I nvent or yI t emclass. However, there is no sensible implementation for this methodin I nvent or yI t em, because each different kind of item has its own requirements. One

    approach may be to leave the method empty in the I nvent oryI t emclass:publ i c abst r act cl ass I nvent oryI t em{

    publ i c bool ean i sRent abl e( ) ; {return true;

    }}

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    46/419Oracle10g: Java Programming 12-6

    The Need for Abstract Methods (continued)

    This approach is not good enough because it does not force each concrete subclass tooverride the method. For example, in the Vcr class, if the user forgets to override thei sRent abl e( ) method, then what will happen if the user calls the method on aVcrobject? The i sRent abl e( ) method in I nvent or yI t emwill be called and alwaysreturn t rue. This is not the desired outcome. The solution is to declare the method as

    abstract, as shown on the next page.

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    47/419Oracle10g: Java Programming 12-7

    12-7 Copyright © 2004, Oracle. All rights reserved.

    Defining Abstract Methods

    • Use the abstract keyword to declare a method asabstract:

     –  Provide the method signature only.

     –  The class must also be abstract.

    • Why is this useful?

     –  Declare the structure of a given class wi thout

    providing complete implementation of every

    method. public abstract class InventoryItem {

     public abstract boolean isRentable();

    Defining Abstract Methods

    To declare a method as abstract in Java, prefix the method name with theabst r act

    keyword as follows:publ i c abst r act cl ass I nvent or yI t em {

    abst r act bool ean i sRent abl e( ) ;…

    }

    When you declare an abst r act method, you provide only the signature for the method,

    which comprises its name, its argument list, and its return type. You do not provide a bodyfor the method. Each concrete subclass must override the method and provide its own body.

     Now that the method is declared as abstract, a subclass must provide an implementation of

    that method.

    Abstract classes can contain methods that are not declared as abstract. Those methods can be

    overridden by the subclasses but it is not mandatory.

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    48/419Oracle10g: Java Programming 12-8

    12-8 Copyright © 2004, Oracle. All rights reserved.

    Defining and Using Interfaces

    •  An interface is like a fully abstract class: –   All i ts methods are abstract.

     –   All variables are public static final.

    •  An interface lists a set of method signatures

    without any code details.

    •  A class that implements the interface must

    provide code details for all the methods of the

    interface.•  A class can implement many interfaces but can

    extend only one class.

    What Is an Interface?

    An interface is similar to an abstract class, except that it cannot have any concrete methods

    or instance variables. It is a collection of abstract method declarations and constants; that is,st at i c f i nal variables. It is like a contract that the subclass must obey.

    Any class that implements an interface must implement some or all of the methods that are

    specified in that interface. If it does not implement all of the methods, then the class is an

    abstract class and a subclass of the abstract class must implement the remaining abstract

    methods.

    A class can implement many interfaces but can extend only one class. Java does not supportinheritance from multiple classes, but it does support implementing multiple interfaces. For

    example:

    cl ass Movi e ext ends I nvent or yI t em i mpl ement s Sor t abl e, Li st abl e {…

    }

    As demonstrated earlier, Movi e inherits all of the attributes and behaviors ofI nvent oryI t em. In addition, it now must provide implementation details for all of themethods that are specified in the Sor t abl e and Li st abl e interfaces. Those methods can

     be used by other classes to implement specific behaviors such as a sort routine.

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    49/419Oracle10g: Java Programming 12-9

    12-9 Copyright © 2004, Oracle. All rights reserved.

    Examples of Interfaces

    • Interfaces describe an aspect of behavior thatdifferent classes require.

    • For example, classes that can be steered support

    the “ steerable” interface.

    • Classes can be unrelated.

    SteerableNonsteerable

    Examples of Interfaces

    Interfaces describe an aspect of behavior that many different classes require. The name of an

    interface is often an adjective such as St eer abl e, Tr aceabl e, Sor t abl e, and so on.This is in contrast to a class name, which is usually a noun such asMovi e or Cust omer .

    The St eer abl e interface may include such methods as t ur nRi ght ( ) , t ur nLef t ( ) ,r et ur nCent er ( ) , and so on. Any class that needs to be steerable may implement theSt eerabl e interface.

    The classes that implement an interface may be completely unrelated. The only thing that

    they may have in common is the need to be steered.

    For example, the core Java packages include a number of standard interfaces such asRunnabl e, Cl oneabl e, and Act i onLi st ener . These interfaces are implemented byall types of classes that have nothing in common except the need to beCl oneabl e, or toimplement an Act i onLi st ener .

    Instructor Note

    Interface is a way to bypass the multiple inheritance restriction that Java has.

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    50/419Oracle10g: Java Programming 12-10

    12-10 Copyright © 2004, Oracle. All rights reserved.

    Creating Interfaces

    • Use the interface keyword:

    •  Al l methods are public abstract.

    •  Al l variables are public static final.

     public interface Steerable {

    int MAXTURN = 45;

    void turnLeft(int deg);

    void turnRight(int deg);

    }

    Creating Interfaces

    You can define an interface by using the i nt er f ace keyword. All methods that arespecified in an interface are implicitly publ i c and abst r act . Any variables that arespecified in an interface are implicitly publ i c, st at i c, and f i nal ; that is, they are

    constants.

    Therefore, the interface definition that is shown in the slide is equivalent to the followingdefinition, where the publ i c, st at i c, f i nal , and abst r act keywords have been

    specified explicitly.

    publ i c i nt er f ace St eer abl e {publ i c st at i c f i nal i nt MAXTURN = 45;publ i c abst r act voi d t ur nLef t ( i nt deg) ;publ i c abst r act voi d t ur nRi ght ( i nt deg) ;

    }

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    51/419Oracle10g: Java Programming 12-11

    Creating Interfaces (continued)

    Because interface methods are implicitly publ i c and abst r act , it is a generally

    accepted practice not to specify those access modifiers. The same is true for variables.Because they are implicitly publ i c, st at i c, and f i nal ( in other words, constants), you

    must not specify those modifiers.

    Instructor Note

    Every field declaration in the body of an interface is implicitlypubl i c, st at i c, andf i nal . It is permitted, but strongly discouraged as a matter of style, to redundantly specify

    one or all of these modifiers for such fields.

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    52/419Oracle10g: Java Programming 12-12

    12-12 Copyright © 2004, Oracle. All rights reserved.

    Implementing Interfaces

    Use the implements keyword:

     public class Yacht extends Boat

    implements Steerable {

     public void turnLeft(int deg) {…}

     public void turnRight(int deg) {…}

    }

    Implementing Interfaces

    The slide shows an example of a Yacht class, that implements the St eer abl e interface. Yacht must implement some or all of the methods in any interface that it implements; inthis case, Yacht may implement t ur nLef t ( ) and t ur nRi ght ( ) .

    A class can implement more than one interface by specifying a list of interfaces separated by

    commas. Consider the following example:publ i c cl ass Yacht

    ext ends Boat

    i mpl ement s St eer abl e, Taxabl e {…}

    Here, the Yacht class implements two interfaces: St eer abl e and Taxabl e. This meansthat the Yacht class must implement all the methods that are declared in both St eer abl eand Taxabl e.

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    53/419Oracle10g: Java Programming 12-13

    12-13 Copyright © 2004, Oracle. All rights reserved.

    Sort: A Real-World Example

    • Is used by several unrelated classes• Contains a known set of methods

    • Is needed to sort any type of object

    • Uses comparison rules that are known only to the

    sortable object

    • Supports good code reuse

    Sort

    A sort is a classic example of the use of an interface. Many completely unrelated classes

    must use a sort. A sort is a well-known and well-defined process that does not need to bewritten repeatedly.

    A sort routine must provide the ability to sort any object in the way that fits that particularobject. The traditional programming approach dictates several subroutines and an ever-growing decision tree to manage each new object type. By using good OO programmingtechnique and interfaces, you can eliminate all of the maintenance difficulties that areassociated with the traditional approach.

    The Sor t abl e interface specifies the methods that are required to make the sort work oneach type of object that needs to be sorted. Each class implements the interface based on itsspecific sorting needs. Only the class needs to know its object comparison, or sorting rules.

    Implementing the sort in the OO way provides a model that supports very good code reuse.The sort code is completely isolated from the objects that implement the sort.

    Instructor Note

    Use the sort examples to demonstrate. Open theDemo. j ws . There are two projects: Sortand ExtendedSort. Start with the Sort project and launch theSor t Appl i cat i on. j avafor a simple demonstration. Use the ExtendedSort project for a more complex

    demonstration. Launch the Ext endedSor t Appl i cat i on. j ava file to demonstrate adouble sort application.

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    54/419Oracle10g: Java Programming 12-14

    12-14 Copyright © 2004, Oracle. All rights reserved.

    Overview of the Classes

    • Created by the sort expert:

    • Created by the movie expert:

     public class

     MyApplication

     public class Movie

    implements Sortable

     public interface

    Sortable

     public abstract

    class Sort

    Overview of the Classes

    The slide shows the three classes and one interface that are involved in sorting a list ofvideos. The classes are divided into two categories:

    • Classes that are created by the sort expert, who knows all about sort algorithms butnothing about individual objects that people may want to sort

    • Classes that are created by the movie expert, who knows all about movies, but nothingabout sort algorithms

    You see how interfaces can separate these two types of developers, enabling the separationof unrelated areas of functionality.

    Classes and Interfaces Used by the Example• The Sor t abl e interface declares one method: compare( ) . This method must be

    implemented by any class that wants to use the sort class methods.• The Sor t class is an abst r act class that contains sor t Obj ect s( ) , which is a

    method to sort an array of objects. Most sort algorithms work by comparing pairs ofobjects. sor t Obj ect s( ) does this comparison by calling the compar e( ) methodon the objects in the array.

    • The Movi e class implements the Sor t abl e interface. It contains a compare( )method that compares two Movi e objects.

    •   MyAppl i cat i on represents any application that must sort a list of movies. It can bea form displaying a sortable list of movies.

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    55/419Oracle10g: Java Programming 12-15

    12-15 Copyright © 2004, Oracle. All rights reserved.

    How the Sort Works

     MyApplication passes

    an array of movies toSort.sortObjects().

    sortObjects()

    asks a movie tocompare itself with

    another movie.

    The movie

    returns theresult of the

    comparison.

    sortObjects()

    returns the

    sorted list.

    1

    23

    4

    Sort

    Movie

    MyApplication

    How the Sort Works

    The slide shows the process of sorting a list of objects. The steps are as follows:

    1. The main application passes an array of movies toSor t . sor t Obj ect s( ) .2.   sor t Obj ect s( ) sorts the array. Whenever sor t Obj ect s( ) needs to compare

    two movies, it calls the compare( ) method of one movie, passing it with the other

    movie as a parameter.3. The movie returns the results of the comparison tosor t Obj ect s( ) .4.   sor t Obj ect s( ) returns the sorted list.

    Instructor NoteThe j ava. l ang. Comparabl e interface that is used withCol l ect i ons. sor t ( Li st ) from the j ava. ut i l  package provides the developerwith ready-made sort functionality. The class implementing theCompar abl e interfaceonly needs to implement an i nt compar eTo( Obj ect o) method, that returns a –1, 0,

    or 1 for a less than, equal to, or greater than result, respectively.

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    56/419Oracle10g: Java Programming 12-16

    12-16 Copyright © 2004, Oracle. All rights reserved.

    The Sortable Interface

    Specifies the compare() method:

     public interface Sortable {

    // compare(): Compare this object to another object

    // Returns:

    // 0 if this object is equal to obj2

    // a value < 0 if this object < obj2

    // a value > 0 if this object > obj2

    int compare(Object obj2);

    }

    The Sortable Interface

    The Sor t abl e interface specifies all of the methods and constants that are required for aclass to be sortable. In the example, the only method iscompare( ) .

    Any class that implements Sor t abl e must provide a compare( ) method that accepts anObj ect argument and returns an i nt .

    The result of the compare( ) method is as follows:

    Note: It is entirely up to the implementer of compare( ) to determine the meaning of

    “greater than,” “less than,” and “equal to.”

    Value Meaning 

    Positive integer This object is greater than the argument.

     Negative integer This object is less than the argument.

    Zero This object is equal to the argument.

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    57/419Oracle10g: Java Programming 12-17

    12-17 Copyright © 2004, Oracle. All rights reserved.

    The Sort Class

    Holds sortObjects():

     public abstract class Sort {

     public static void sortObjects(Sortable[] items) {

    // Step through the array comparing and swapping;

    // do this length-1 times

    for (int i = 1; i < items.length; i++) {

    for (int j = 0; j < items.length - 1; j++) {

    if (items[j].compare(items[j+1]) > 0) {

    Sortable tempitem = items[j+1];

    items[j+1] = items[j];

    items[j] = tempitem; } } } } }

    The Sort Class

    The Sor t class contains the sor t Obj ect s( ) method that sorts an array of Sor t abl eobjects. sor t Obj ect s( ) accepts an array of Sor t abl e as its argument. It is legal

    syntax to specify an interface type for a method’s argument; in this case, it ensures that themethod will be asked to sort only objects that implement theSor t abl e interface. In theexample, sor t Obj ect s( ) executes a simple sort that steps through the array several

    times, and compares each item with the next one and swaps them if necessary.

    When sor t Obj ect s( ) needs to compare two items in the array, it calls compare( ) on

    one of the items, passing the other item as the argument. Note that sor t Obj ect s( ) knows nothing about the type of object that it is sorting. Itknows only that they are Sor t abl e objects, and therefore it knows that it can call acompar e( ) method on any of the objects, and it knows how to interpret the results.

    Interface as a Contract

    You can think of an interface as a contract between the object that uses the interface and the

    object that implements the interface. In this case, the contract is as follows:• The Movi e class (the implementer) agrees to implement a method called

    compare( ) , with parameters and return value specified by the interface.

    • The Sor t class (the user) agrees to sort a list of objects in the correct order.

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    58/419Oracle10g: Java Programming 12-18

    12-18 Copyright © 2004, Oracle. All rights reserved.

    The Movie Class

    Implements Sortable:

     public class Movie extends InventoryItem 

    implements Sortable {

    String title;

     public int compare(Object movie2) {

    String title1 = this.title;

    String title2 = ((Movie)movie2).getTitle();

    return(title1.compareTo(title2));

    }}

    The Movie Class

    The Movi e class implements the Sor t abl e interface. To call Sor t . sor t Obj ect s( ) ,it must implement the Sor t abl e interface, and if it implements the Sor t abl e interface,then it must implement the compar e( ) method; this is the contract. The compare( )method takes an Obj ect as an argument and compares it with the object on which it was

    called.

    In this case, you use the St r i ng compar eTo( ) method to compare the two title strings.compareTo( ) returns a positive integer, a negative integer, or zero depending on the

    relative order of the two objects. When implementingcompare( ) , you can compare thetwo objects in any way you like, as long as you return an integer that indicates their relative

    sort order.

    Note: In the example, movi e2 is an Obj ect . So, it must be cast to Movi e before you cancall get Ti t l e( ) to get its title.

  • 8/20/2019 Oracle10g Java Programming Instructor Guide - Volume 2.pdf

    59/419Oracle10g: Java Programming 12-19

    12-19 Copyright © 2004, Oracle. All rights reserved.

    Using the Sort

    Call Sort.sortObjects(Sortable []) with an arrayof Movie as the argument:

    class myApplication {

     Movie[] movielist;

    … // build the array of Movie

    Sort.sortObjects(movielist);

    }

    Using the Sort

    To use the sort, you call Sor t . sor t Obj ect s( Sor t abl e [ ] ) from your application,

     passing the array of objects that you want sorted. Each object that you want to sort mustimplement the Sor t abl e interface and provide