Oracle 10g Java Programming.pdf

download Oracle 10g Java Programming.pdf

of 468

Transcript of Oracle 10g Java Programming.pdf

  • 8/10/2019 Oracle 10g Java Programming.pdf

    1/467

    D17249GC11

    Edition 1.1

    August 2004

    D39813

    Oracle10g: Java Programming

    Student Guide - Volume 1

  • 8/10/2019 Oracle 10g Java Programming.pdf

    2/467

    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 CooperPeter DriverChristian DugasCraig HollisterChika IzumiPete LaseauGlenn MaslenMonica MotleyGayathri Rajagopal

    Publisher

    Poornima G

  • 8/10/2019 Oracle 10g Java Programming.pdf

    3/467

    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

    Oracle10gProducts 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 Objects 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

    iii

  • 8/10/2019 Oracle 10g Java Programming.pdf

    4/467

    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 CLASSPATH Variable 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/10/2019 Oracle 10g Java Programming.pdf

    5/467

    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 if Statement 5-7

    Nesting if Statements 5-8

    Guided Practice: Spot the Mistakes 5-9

    Defining the switch Statement 5-10

    More About the switch Statement 5-12

    Looping in Java 5-13Using the while Loop 5-14

    Using the dowhile Loop 5-15

    Using the for Loop 5-16

    More About the for Loop 5-17

    Guided Practice: Spot the Mistakes 5-18

    The break 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/10/2019 Oracle 10g Java Programming.pdf

    6/467

    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 10gDebugger 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 new Operator 7-7

    Comparing Primitives and Objects 7-8

    Using the null Reference 7-9

    Assigning References 7-10

    Declaring Instance Variables 7-11

    Accessing public 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/10/2019 Oracle 10g Java Programming.pdf

    7/467

    Setting the CLASSPATH with Packages 7-29

    Access Modifiers 7-30

    Summary 7-32

    Practice 7: Overview 7-33

    8 Object Life Cycle and Inner Classes

    Objectives 8-2Overloading Methods 8-4

    Using the this 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

    final Variables, Methods, and Classes 8-10

    Reclaiming Memory 8-11

    Using the finalize() 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 Calendar 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 String? 9-3

    Creating a String 9-4

    Concatenating Strings 9-5

    Performing Operations on Strings 9-6

    Performing More Operations on Strings 9-7

    Comparing String 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 SimpleDateFormat Class 9-15Using the MessageFormat Class 9-16

    Using DecimalFormat 9-17

    Guided Practice 9-18

    Using Regular Expressions 9-20

    vii

  • 8/10/2019 Oracle 10g Java Programming.pdf

    8/467

  • 8/10/2019 Oracle 10g Java Programming.pdf

    9/467

    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 ArrayList and Hashtable 11-21

    Using Iterators 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 Sortable Interface 12-16

    The Sort Class 12-17

    The Movie Class 12-18

    Using the Sort 12-19

    Using instanceof 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/10/2019 Oracle 10g Java Programming.pdf

    10/467

    Cleaning Up with a finally 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 JPanel Containers 14-27Adding 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/10/2019 Oracle 10g Java Programming.pdf

    11/467

    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 JList 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 ResultSet 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/10/2019 Oracle 10g Java Programming.pdf

    12/467

    Mapping Database Types to Java Types 16-26

    Handling an Unknown SQL Statement 16-28

    Handling Exceptions 16-29

    Managing Transactions 16-30

    The PreparedStatement Object 16-31

    How to Create a PreparedStatement 16-32

    How to Execute a PreparedStatement 16-33Maximize Database Access 16-34

    Connection Pooling 16-35

    Summary 16-38

    Practice 16: Overview 16-39

    17 Deploying Applications 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 .jar 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 Solutions

    Appendix B: Java Language Quick-Reference Guide

    Appendix C: Order Entry Solution

    xii

  • 8/10/2019 Oracle 10g Java Programming.pdf

    13/467

    Preface

  • 8/10/2019 Oracle 10g Java Programming.pdf

    14/467

  • 8/10/2019 Oracle 10g Java Programming.pdf

    15/467

    Preface - 3

    Profile

    Prerequisites

    Required: Previous experience with another 3GL programming language, preferably a structured

    language such as Pascal or C

    Suggested: Familiarity with basic HTML

    How This Course Is OrganizedOracle 10g: Java Programmingis an instructor-led course featuring lectures and hands-on exercises.

    Online demonstrations and written practice sessions reinforce the concepts and skills introduced.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    16/467

    Preface - 4

    Related Publications

    Oracle Publications

    Title Part Number

    Oracle 10g: Build J2EE Applications (inClass course) D17247GC10

    Oracle JDeveloper 10g: Build Applications with Oracle ADF (inClass course) D16975GC10

    Oracle JDeveloper Handbook (Oracle Press)

    Additional Publications

    System release bulletins

    Installation and users guides

    Read-me files

    International Oracle Users Group (IOUG) articles

    Oracle Magazine

  • 8/10/2019 Oracle 10g Java Programming.pdf

    17/467

    Preface - 5

    Typographic Conventions

    Typographic Conventions In Text

    Convention Element Example

    Bold Emphasized words and phrases

    in Web content only

    To navigate within this application, do not

    click the Back and Forward buttons.

    Bold italic Glossary terms (if there is a

    glossary)

    The algorithm inserts the new key.

    Brackets Key names Press [Enter].

    Caps and

    lowercase

    Buttons,

    check boxes,

    triggers,

    windows

    Click the Executable button.

    Select the Registration Required check

    box.

    Assign a When-Validate-Item trigger.

    Open the Master Schedule window.

    Carets Menu paths Select File > Save.

    Commas Key sequences Press and release these keys one at a

    time:

    [Alt], [F], [D]

  • 8/10/2019 Oracle 10g Java Programming.pdf

    18/467

  • 8/10/2019 Oracle 10g Java Programming.pdf

    19/467

    Preface - 7

    Typographic Conventions (continued)

    Typographic Conventions in Navigation Paths

    This course uses simplified navigation paths, such as the following example, to direct you through

    Oracle Applications.

    Example:

    Invoice Batch Summary

    (N) Invoice > Entry > Invoice Batches Summary (M) Query > Find (B) Approve

    This simplified path translates to the following:

    1. (N) From the Navigator window, select Invoice > Entry > Invoice Batches Summary.

    2. (M) From the menu, select Query > Find.

    3. (B) Click the Approve button.

    Notation:

    (N) = Navigator (I) = Icon

    (M) = Menu (H) = Hyperlink

    (T) = Tab (B) = Button

  • 8/10/2019 Oracle 10g Java Programming.pdf

    20/467

  • 8/10/2019 Oracle 10g Java Programming.pdf

    21/467

    Copyright 2004, Oracle. All rights reserved.

    Introduction

  • 8/10/2019 Oracle 10g Java Programming.pdf

    22/467Oracle10g: Java Programming I-2

    Copyright 2004, Oracle. All rights reserved.

    Objectives

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

    Write stand-alone applications with the Java

    programming language

    Develop and deploy an application

    Build, generate, and test application components

    by using Oracle JDeveloper 10g

  • 8/10/2019 Oracle 10g Java Programming.pdf

    23/467Oracle10g: Java Programming I-3

    Copyright 2004, Oracle. All rights reserved.

    Course Overview

    This course teaches you how to write Javaapplications.

    You also learn how to build, debug, and deploy

    applications by using Oracle JDeveloper 10g.

    The development environment is Oracle

    JDeveloper 10g and the Oracle Database.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    24/467

  • 8/10/2019 Oracle 10g Java Programming.pdf

    25/467

    Copyright 2004, Oracle. All rights reserved.

    Introducing the Java

    and Oracle Platforms

  • 8/10/2019 Oracle 10g Java Programming.pdf

    26/467Oracle10g: Java Programming 1-2

    Copyright 2004, Oracle. All rights reserved.

    Objectives

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

    Identify the key elements of Java

    Describe the Java Virtual Machine (JVM)

    Examine how Java is used to build applications

    Identify the key components of the J2SE Java

    Development Kit (known as JDK or SDK)

    Describe Java deployment options

    Lesson AimThis lesson introduces the background and usefulness of the Java language. It discusses Javas

    position with the Oracle10g. Java is the programming language of choice for Internet

    applications. It has gained this status because of its robust nature, the object-orientation of the

    language, the depth of its predefined classes, and its write once, run anywhere deployment

    model. You learn how Java supports object-oriented programming and architectural neutral

    deployment.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    27/467Oracle10g: Java Programming 1-3

    Copyright 2004, Oracle. All rights reserved.

    What Is Java?

    Java: Is a platform and an object-oriented language

    Was originally designed by Sun Microsystems for

    consumer electronics

    Contains a class library

    Uses a virtual machine for program execution

    What Is Java?Designed by Sun Microsystems

    Java is a platform and an object-oriented programming language, which was originallydeveloped by Sun Microsystems, Inc. It was created by James Gosling for use in consumerelectronics. Because of the robustness and platform-independent nature of the language, Javasoon moved beyond the consumer electronics industry and found a home on the World WideWeb. Java is a platform, which means that it is a complete development and deploymentenvironment.

    Class Libraries

    Java contains a broad set of predefined classes, which contain attributes and methods that handle

    most of the fundamental requirements of programs. Window management, input/output, andnetwork communication classes are included in the Java Developers Kit (JDK). The classlibrary makes Java programming significantly easier and faster to develop when compared withother languages. JDK also contains several utilities to facilitate development processes. Theseutilities handle operations, such as debugging, deployment, and documentation.

    Java Uses a Virtual Machine

    One of the key elements of the Java language is platform independence. A Java program that iswritten on one platform can be deployed on any other platform. This is usually referred to aswrite once, run anywhere (WORA). This task is accomplished through the use of the JavaVirtual Machine (JVM). JVM runs on a local machine and interprets the Java bytecode andconverts it into platform-specific machine code.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    28/467Oracle10g: Java Programming 1-4

    Copyright 2004, Oracle. All rights reserved.

    Key Benefits of Java

    Object-oriented Interpreted and platform-independent

    Dynamic and distributed

    Multithreaded

    Robust and secure

    Key Benefits of JavaObject-Oriented

    An object is an entity that has data attributes, plus a set of functions that are used to manipulate

    the object. Java is a strongly typed language, which means that almost everything in Java is an

    object. The main exceptions are the primitive data types, such as integers and characters.

    Interpreted and Platform Independent

    Java programs are interpreted to the native machines instruction set at run time. Because Java

    executes under the control of a JVM, Java programs can run on any operating system that

    provides a JVM.

    Dynamic and DistributedJava classes can be downloaded dynamically over the network when required. In addition, Java

    provides extensive support for client-server and distributed programming.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    29/467Oracle10g: Java Programming 1-5

    Key Benefits of Java (continued)

    Multithreaded

    Java programs can contain multiple threads to carry out many tasks in parallel. Multithreading

    capability is built into Java and is under the control of the platform-dependent JVM.

    Robust and Secure

    Java has built-in capabilities to prevent memory corruption. Java automatically manages the

    processes of memory allocation and array bounds checking. It prohibits pointer arithmetic, andrestricts objects to named spaces in memory.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    30/467

  • 8/10/2019 Oracle 10g Java Programming.pdf

    31/467Oracle10g: Java Programming 1-7

    Copyright 2004, Oracle. All rights reserved.

    Platform Independence

    Java source code is stored as text in a .java file. The .java file is compiled into .class files.

    A .class file contains Java bytecodes

    (instructions).

    The bytecodes are interpreted at run time.

    The Java .class file is the executable code.

    Compile

    Movie.java

    JVM

    Running programMovie.class

    (javac) (java)

    Platform IndependenceJava Is an Interpreted Language

    Java program source code is stored in .java files. For example, a Java program dealing withmovies in a video rental company may have files called Movie.java, Customer.java, andRental.java.

    Each .java file is compiled into a corresponding .class file with the same name. Forexample, a Movie.java compiles to at least one class file. (Inner classes is quite common.)But, the public Movie.java compiles to one Movie.class. These.class files contain

    Java bytecodes, which are platform-independent machine instructions.

    Java Virtual Machine (JVM)

    JVM provides the environment for running Java programs. The JVM interprets Java bytecodesinto the native instruction set for the machine on which the program is currently running.

    The same .class files can be executed unaltered on any platform for which a JVM is provided.

    For this reason, JVM is sometimes referred to as a virtual processor.

    Traditional Compiled Languages

    When compiling a traditional language such as C, the code written by the programmer isconverted into machine instructions for the platform on which the compilation takes place. Thiscompiled program can then run only on machines that have the same processor as that on whichit was compiled, such as Intel, SPARC, or Alpha.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    32/467Oracle10g: Java Programming 1-8

    Copyright 2004, Oracle. All rights reserved.

    Using Java with Enterprise

    Internet Computing

    Web

    server

    Application

    server

    PresentationBusiness

    logic

    Servlets

    JavaServer

    Pages (JSPs)

    Enterprise

    JavaBeans (EJB)

    CORBA

    Client Data

    Java and Enterprise Internet ComputingYou can design Java programs as server-based components that form scalable Internet

    applications.

    The currently accepted model for Java Internet computing divides the end-to-end application

    process into several logical tiers. To utilize this model, JavaSoft defined the Java2, Enterprise

    Edition (J2EE). There are four logical tiers:

    Client Tier

    When Java is needed to execute on client machines, it is typically implemented as a browser-

    based application. But a thin client can be just Web pages that are delivered from a server as

    HTML.Presentation Tier

    This is executed on a Web server. Code in this tier handles the applications presentation to the

    client. Common Java features for this function are servlets and JavaServer Pages (JSPs). Servlets

    and JSPs can each generate dynamic HTML for display as Web pages to clients.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    33/467Oracle10g: Java Programming 1-9

    Java and Enterprise Internet Computing (continued)

    Application (Business Logic) Tier

    You can use Java on an application server to implement shareable, reusable business logic as

    application components. A common way to implement this is to use component models, such as

    Enterprise JavaBeans (EJB) and Common Object Request Broker Architecture (CORBA)

    objects. These two components are also to be considered during design time, when a distributed

    environment is required.

    Data Tier

    The data server not only stores data, but can also store and execute Java code, particularly where

    this code is data intensive or enforces validation rules pertaining to the data. You can also use

    Business Components, from Oracles Application Development Framework (ADF), to support

    the data access of your application.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    34/467Oracle10g: Java Programming 1-10

    Copyright 2004, Oracle. All rights reserved.

    Using the Java Virtual Machine

    Operating system

    JVM

    Application

    Running Java ApplicationsAll Java applications run within a Java Virtual Machine (JVM). JVM is invoked differently

    depending on whether the Java program is an application or an applet.

    Applications

    You can run stand-alone applications by invoking a local JVM directly from the operating

    system command line and supplying the name of the main class for the application. After loading

    the applications main class file, JVM runs the program by calling a known entry point in theclass; that is, a public static method called main(...). JVM runs the code by interpreting the

    bytecodes in the Java program and converting bytecode into platform-specific machine

    instructions.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    35/467Oracle10g: Java Programming 1-11

    Running Java Applications (continued)

    Running Java Applets

    A Java applet is a special type of Java program that is used in Web pages. When a Web browser

    reads an HTML page with an applet tag, it downloads the applet over the network to the local

    system and runs the applet in a JVM that is built into the browser. The browser invokes a

    specific call sequence of known methods in the Java applet class to execute the Java code in the

    context of the browsers JVM. The applet entry points differ from the entry point that is used by

    JVM to run stand-alone applications.

    In the case of an applet, the presentation server is not necessarily used. A Java application is

    quite capable, and typically is configured, to connect directly to the business logic.

    Applets are not covered in this course, and are only presented here for completeness. In this

    course, during deployment of your application, you use the Java Web Start product.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    36/467Oracle10g: Java Programming 1-12

    Copyright 2004, Oracle. All rights reserved.

    How Does JVM Work?

    The class loader loads all required classes. JVM uses a CLASSPATH setting to locate class files.

    JVM Verifier checks for illegal bytecodes.

    JVM Verifier executes bytecodes.

    JVM may invoke a Just-In-Time (JIT) compiler.

    Memory Manager releases memory used by the

    dereferenced object back to the OS.

    JVM handles Garbage collection.

    How Does JVM Work?JVM Class Loader

    When a .class file is run, it may require other classes to help perform its task. These classes

    are loaded automatically by the class loader in JVM. The required classes may reside on thelocal disk or on another system across the network. JVM uses theCLASSPATH environment

    variable to determine the location of local .class files. The classpath can be added in run time

    by using the java -cp or -classpath option.

    Classes that are loaded from the network are kept in a separate namespace from those on the

    local system. This prevents name clashes and the replacement or overriding of standard classes,

    malicious or otherwise.

    JVM Verifier

    It is the job of the verifier to make sure that the Java code that is being interpreted does not

    violate any of the basic rules of the Java language and that the code is from a trusted source. A

    trusted source is an option; and if used, the check is not performed.

    This validation ensures that there are no memory access violations or other illegal actions

    performed.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    37/467

  • 8/10/2019 Oracle 10g Java Programming.pdf

    38/467

  • 8/10/2019 Oracle 10g Java Programming.pdf

    39/467

  • 8/10/2019 Oracle 10g Java Programming.pdf

    40/467

  • 8/10/2019 Oracle 10g Java Programming.pdf

    41/467Oracle10g: Java Programming 1-17

    Java Security Layers (continued)

    Bytecode Verifier

    During the execution of a Java program, JVM can import code from anywhere. Java must make

    sure that the imported code is from a trustworthy source. To accomplish this task, the run-time

    system performs a series of checks called bytecode verification.

    Interface-Specific Access

    Built-in classes and methods control access to the local file system and network resources. Theseclasses are restrictive by default. If imported code tries to access the local file system, then the

    security mechanism prompts the user.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    42/467Oracle10g: Java Programming 1-18

    Copyright 2004, Oracle. All rights reserved.

    Deployment of Java Applications

    Client-side deployment: JVM runs stand-alone applications from the

    command line.

    Classes load from a local disk, eliminating the need

    to load classes over a network.

    Server-side deployment:

    Serves multiple clients from a single source

    Is compatible with a multitier model for Internet

    computing.

    Java ApplicationsJava originally gained popular acceptance because of the success of its applets. Today, however,

    it is also possible to write stand-alone applications in Java. A Java application is invoked by

    using a JVM and is not run from within a browser.

    Client-Side Deployment

    Java applications can be deployed to run stand-alone applications within a local operating

    system, from the command line. For example, Java applications can access the local file system

    or establish connections with other machines on the network.

    Server-Side Deployment

    Java applications can also execute on the server machine, as long as a JVM is available on thatplatform. The use of server-side Java applications is compatible with the multitier model for

    Internet computing.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    43/467

  • 8/10/2019 Oracle 10g Java Programming.pdf

    44/467Oracle10g: Java Programming 1-20

    Copyright 2004, Oracle. All rights reserved.

    Java Software Development Kit

    Sun Java J2SE (known as JDK and Java SDK)provides:

    Compiler (javac)

    Core class library

    classes.zip

    rt.jar

    Debugger (jdb)

    Bytecode interpreter: The JVM (java) Documentation generator (javadoc)

    Java Archive utility (jar)

    Others

    J2SE

    Java Software Development KitSun provides the Java 2, Standard Edition (J2SE), which is also known as Java Software

    Development Kit (Java SDK) or the Java Development Kit (JDK). The components that are

    provided by the J2SE include the following:

    The Java compiler is javac. It compiles Java source code into Java bytecodes.

    The Java bytecode interpreter, java, is the engine that runs Java applications.

    The program that generates documentation in HTML from Java source code comments is

    javadoc.

    Core Class Library

    The J2SE provides core Java class in the following class library files: classes.zip located in the jdk_home\lib for JDK 1.1.x or earlier rt.jar located in the jdk_home\jre\lib for Java SDK 1.2.x or later

    Other Java J2SE Tools

    jdb is the Java class debugger. It is similar to the dbx or gdb debuggers on UNIX.

    jar is used to create Java Archive (JAR) files, which are zipped Java programs.

    javah is used to generate C files for native methods.

    javakey supports the generation of certification keys for trusted Java code.

    javap is used to disassemble Java bytecodes into human-readable format.

    native2ascii converts Java source code to Latin 1 characters.

    serialver is used to generate version numbers for classes.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    45/467Oracle10g: Java Programming 1-21

    Copyright 2004, Oracle. All rights reserved.

    Using the Appropriate Development Kit

    Java2 comes in three sizes: J2ME (Micro Edition): Version specifically targeted

    at the consumer space

    J2SE (Standard Edition): Complete ground-up

    development environment for the Internet

    J2EE (Enterprise Edition): Everything in the J2SE

    plus an application server and prototyping tools

    A Size for Every NeedJava 2, Micro Edition

    The technology that Java 2, Micro Edition (J2ME) uses covers the range of extremely tiny

    commodities, such as smart cards or a pager, all the way up to the set-top box, which is an

    appliance that is almost as powerful as a computer. Like the other editions, the J2ME platform

    maintains the qualities for which Java technology has become famous.

    Java 2, Standard Edition

    The J2SE technology has revolutionized computing with the introduction of a stable, secure, and

    feature-complete development and deployment environment that is designed from the ground up

    for the Web. It provides cross-platform compatibility, safe network delivery, and smart card tosupercomputer scalability. It provides software developers with a platform for rapid application

    development.

    Java 2, Enterprise Edition

    The J2EE platform is intended as a proof of concept, and a guide for implementations in the

    application server marketplace. The J2EE SDK includes a J2EE application server and various

    tools to help developers prototype J2EE applications.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    46/467Oracle10g: Java Programming 1-22

    Copyright 2004, Oracle. All rights reserved.

    Integrated Development Environment

    Development

    UML

    ADF

    XML

    SCM

    Debug

    Exchange

    Database

    HTML

    Deployment

    Synchronized changes

    Integrated Development EnvironmentThe add-in API architecture of Integrated Development Environment (IDE) means that all the

    tool components (for example, navigator, editor, and modeller) share memory models and event

    systems. In this way, an update in one tool is notified to another tool so that it can refresh its

    image or take other appropriate actions.

    In Oracle 10g, the JDeveloper IDE was developed in pure Java. Synchronization between model

    and code can be set so that you can decide to work by using one or the other user interface.

    Customizable Environment

    You can customize the JDeveloper Integrated Development Environment and arrange its look to

    better suit your project needs and programming style. To suit the IDE to your individual taste,you can:

    Change the look and feel of the IDE

    Create and manipulate custom navigators

    Customize the Component Palette

    Customize the IDE environment

    Select JDevelopers embedded J2EE server

    Arrange the windows in the IDE

  • 8/10/2019 Oracle 10g Java Programming.pdf

    47/467Oracle10g: Java Programming 1-23

    Copyright 2004, Oracle. All rights reserved.

    Exploring the JDeveloper Environment

    System Navigator Code Editor Property Inspector

    Component Palette

    The Oracle JDeveloper 10gEnvironmentJDeveloper contains four major user interface components. These components are what you use

    to edit code, design and manage the user interface, and navigate around your program.

    Component Palette

    Properties are attributes that define how a component appears and responds at run time. In

    JDeveloper, you set a components initial properties during design time, and your code can

    change those properties at run time.

    System Navigator

    System Navigator is made up of two components. The Navigator pane shows a list of files or

    classes in a project. The files may be Java source files, .class files, graphics files, HTML,XML documents, and so on. The Structure pane lists all the methods, fields, and graphical user

    interface (GUI) components in a selected class.

    Code Editor

    Editors are where most of the work takes place; this is where you write code and design user

    interfaces. Open an editor by double-clicking the item you want to edit or view.

    Property Inspector

    Property Inspector is the window that shows the properties and events associated with a selected

    component in the design region of a viewer.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    48/467Oracle10g: Java Programming 1-24

    Copyright 2004, Oracle. All rights reserved.

    Oracle10gProducts

    Oracle 10gProductsOracle Database 10g

    The Oracle Database manages all your information: Word documents, Excel spreadsheets, XML,

    images, and so on. Oracle Development Suite 10gtools can automatically reuse the database

    structure and its integrity constraints, which reduces the amount of manual coding.

    Oracle Application Server 10g

    The Oracle Application Server 10gruns all your applications: J2EE applications, Forms,

    wireless, portals, and business intelligence. Using Oracle Application Server 10g, all applications

    that are developed with Oracle Development Suite 10g can be deployed and managed in a single

    application server.Oracle Developer Suite 10g

    Oracle Developer Suite 10g leverages the infrastructure that is offered by Oracle Application

    Server 10g and Oracle Database 10g enabling developers to build scalable, secure, and reliable

    e-business applications quickly and easily. The suite provides a complete and highly productive

    development environment for building applications. Oracle JDeveloper 10g is now available as a

    separate product and not just as part of the developer suite product.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    49/467Oracle10g: Java Programming 1-25

    Copyright 2004, Oracle. All rights reserved.

    Summary

    In this lesson, you should have learned the following: Java code is compiled into platform-independent

    bytecodes.

    Bytecodes are interpreted by JVM.

    Java applications can be stand-alone or

    implemented across an Internet-computing model.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    50/467

  • 8/10/2019 Oracle 10g Java Programming.pdf

    51/467

    Copyright 2004, Oracle. All rights reserved.

    Defining Object-Oriented Principles

  • 8/10/2019 Oracle 10g Java Programming.pdf

    52/467Oracle10g: Java Programming 2-2

    Copyright 2004, Oracle. All rights reserved.

    Objectives

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

    Define objects and explain how they are used

    Associate objects so that they can communicate

    and interact via messages

    Define classes and explain how they are used

    Describe object-oriented (OO) principles: classes,

    objects, and methods Describe the value of Reusable Software

    Components

    Examine the OO model that is used in this course

    Lesson AimThis lesson introduces the concepts of classes and objects, which are the foundation to the

    object-oriented approach to building applications. It explains the benefits and implementation of

    object-oriented principles. It introduces Classes, Objects, and Methods and contrasts OO

    principles with traditional programming techniques. This lesson defines the terms Abstraction,

    Encapsulation, Inheritance, and Polymorphism, and explains the benefits of each of these

    principles. The course application class structure is presented and a simple use case scenario is

    discussed to provide context for using an object defined by the class model.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    53/467Oracle10g: Java Programming 2-3

    Overview of Object-Oriented Programming

    Object-oriented programming (OOP) is a relatively new paradigm for creating computer

    programs that are adaptable, reusable, and can stand the test of time. The functionality comes

    from the design of discrete classes that contain information about objects as well as expected

    behaviors. In an OO program, objects send messages to one another and expect certain behaviors

    or messages in return.

    A good example of object orientation is the personal computer (PC). Although this is not a

    programming example, it serves as an example of what OOP can deliver in a programming

    environment.

    Each PC is made up of components that are manufactured by several unrelated companies. Each

    component is built to a specification that includes information and behaviors. A CD drive, for

    example, is expected to return data from a CD when the operating system asks for it. The PC

    manufacturer does not need to be concerned with the internal workings of the CD drive, only that

    it responds to requests appropriately.

    In the same way, an OO program may make calls to objects without knowing all the details of

    the objects. The program simply expects to get information or produce a specific behavior. By

    defining each of these objects separately, the internal workings of each object can change as longas the way they are called and how they behave stay the same.

    OOP uses a number of techniques to achieve adaptability including abstraction, encapsulation,

    inheritance, and polymorphism. Each of these topics is discussed in the next few pages.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    54/467Oracle10g: Java Programming 2-4

    Copyright 2004, Oracle. All rights reserved.

    What Is Modeling?

    Models perform the following functions: Describe exactly what the business needs

    Facilitate discussion

    Prevent mistakes

    Modeling and implementation are treated

    separately.

    Before coding can begin, the model must be

    correct.

    The House-Building MetaphorImagine someone who wants to have a house built. Initially, the house exists only in the minds of

    the future home owners as ideas, or pieces of various dreams. Sometimes, the future inhabitants

    may not even know what they want, or know whether what they want is even feasible. Dreams

    may be full of internal contradictions and impossibilities. This is not a problem in the dream

    world; in the physical realm, any inconsistencies and obstacles must be resolved before someone

    can construct the house.

    A building contractor needs a solid set of blueprints of the house with a description of the

    materials to be used, the size of the roof beams, the capacity of the plumbing, and so on. The

    contractor follows the plan, and has the knowledge to construct what is on the blueprint. But how

    do the ideas of the home owner become the blueprint for the contractor? This is where thearchitect comes in.

    The architect is the intermediary between the sponsor and the contractor. He or she is trained in

    the skills of translating ideas into models. The architects skills in extracting ideas, putting them

    down in a format that enables discussion and analysis, giving advice, describing sensible options,

    documenting them, and confirming them with the home owners, are the cornerstones to

    providing the future home owners with a plan of the home they want.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    55/467Oracle10g: Java Programming 2-5

    Copyright 2004, Oracle. All rights reserved.

    What Are Classes and Objects?

    A class: Models an abstraction of objects

    Defines the attributes and behaviors of

    objects

    Is the blueprint that defines an object

    An object:

    Is stamped out of the class mold

    Is a single instance of a class

    Retains the structure and behavior

    of a class

    What Is an Object?An object is something tangible, something that can be seen or touched, or something

    that can be alluded to and thought about.

    Object-oriented programs consist of several objects. These objects communicate with each other

    by sending messages from one object to another. In a true object-oriented program, that is all you

    have: a coherent group of communicating objects. New objects are created when needed, old

    ones are deleted, and existing objects carry out operations by sending messages.

    Some examples of objects in an OO program are Customer, Invoice, RentalAgreement, Video,

    and so on. Each of these objects holds information about itself and performs certain behaviors. A

    customer has a name, address, and phone number. A customer may also rent a video, return a

    video, pay a bill, and have other behaviors.

    What Are Classes?

    A class is a model of abstraction from real-world objects. A class defines the properties and

    behavior of a set of objects. A class denotes a category of objects and acts as a blueprint for

    creating that type of object.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    56/467Oracle10g: Java Programming 2-6

    Copyright 2004, Oracle. All rights reserved.

    An Objects Attributes Maintain Its State

    Objects have knowledge about their current state. Each piece of knowledge is called an attr ibute.

    The values of attributes dictate the objects state.

    Attribute: Ink amount

    Attribute: Cash available

    Object: My blue pen

    Object: Acme Bank ATM

    An Objects Attributes Maintain Its StateAll the data that an OO system requires must be located in attributes of the existing objects.

    Some objects have little or no data, whereas other objects have a lot of data; it depends entirely

    on the operations that the object is to perform.

    The collection attributes that are defined in an object determine its internal structure; in essence,

    the object is a composite data structure, which is often called a user-defined type.

    The values that are held in the attributes, at a given point in time, represent the current state of

    the object. As the values of attributes change, over time, the state of the object changes. The state

    of an object is remembered as long as the object exists in the system (memory). The attribute

    values are typically altered by executing an object method in response to some internal or

    external event. It is the job of the object code to maintain the integrity of the objects state; that

    is, to ensure that the object state is valid for that object.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    57/467Oracle10g: Java Programming 2-7

    An Objects Attributes Maintain Its State (continued)

    Typical Attributes

    As with operations, different objects store different attributes. For example, theAcme Bank

    ATM object has attributes such as cash available, cards recognized, ATM code, and so on. The

    blue pen object has attributes such as amount of ink remaining, diameter of nib, length of

    stem, and so on.

    Attributes are often deduced after you have decided what operations the object will supply. Afteryou know what the object must do, you are much better positioned to decide what attributes the

    object must store to support these operations. Often, the attributes of an object are initially

    known and can be used to define the type of operations that are required to maintain their value.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    58/467Oracle10g: Java Programming 2-8

    Copyright 2004, Oracle. All rights reserved.

    Objects Have Behavior

    An object exists to provide behavior (functionality)to the system.

    Each distinct behavior is called an operat ion.

    Operation: Write

    Operation: Withdraw

    Object: My blue pen

    Object: Acme Bank ATM

    Objects Have BehaviorThe major purpose that is served by objects is performing operations in the system in which theyexist. Object technology decomposes a system entirely into objects; all the interactions betweenthe system and the outside world, and all the internal computations of the system, are carried outby the operations (or methods) of objects.

    Typical Operations

    Different objects naturally perform different operations. For example, theAcme Bank ATM

    object has operations such as withdraw, print receipt, swipe card, and so on. Alternatively, themy blue pen object has operations such as write, leak ink, and so on.

    For each object, you have to ask yourself: What does this object do for me? In other words,

    what services does this object supply for the other objects in the system? To do this, you musthave an idea about how the object will be used in the system; otherwise, you may end updefining several operations for each object, which is clearly unsatisfactory. It is important tounderstand how the object will be used in the system and to specify only the operations that arerelevant for that mode of usage.

    You must also ask how the state of the object is changed; that is, How do the values that areheld in the object attribute get modified? This question enables you to define operations tomaintain the internal details of an object.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    59/467Oracle10g: Java Programming 2-9

    Copyright 2004, Oracle. All rights reserved.

    Objects Are Modeled as Abstractions

    A Java object is modeled as an abstractrepresentation of a real-world object.

    Model only those attributes and operations that

    are relevant to the context of the problem.

    Real-world attributes/operations that you may no twant to model:

    Attributes: Ink color

    Operations: Refill, change color, point, write

    Context: Product catalog

    Real-world attributes/operations that you may want to model:

    Attributes: Model, manufacturer, price

    Operations: Change price

    Objects Are Modeled as AbstractionsHow do you decide what operations and attributes are relevant to the model of the my blue

    pen object? The answer is simple. You must understand how the object will be used by the other

    objects in the context of this particular system. You model the object as an abstraction of the

    real-world example in the context in which it exists.

    For example, in the context of a product catalog, the relevant attributes of a pen are reported,such as the model or name, price, and the manufacturer (for example, Mont Blanc). Theoperations that are relevant to this catalog would be to change the price of this pen.

    You may need to know whether the pen can be used to write text, be refilled, or have its inkcolor changed by replacing a cartridge. However, these latter operations are more relevant to the

    way the pen is used by the customer who is purchasing the pen, and therefore the refill, write,change ink operations are not relevant to the catalog application context and must not bemodeled. When deciding on the attributes and operations for an object, always ask whether theyhave relevance in the domain of the application; always evaluate the attributes and operations inthe application context; that is, Are they required to successfully implement the system to meetbusiness requirements?

  • 8/10/2019 Oracle 10g Java Programming.pdf

    60/467

  • 8/10/2019 Oracle 10g Java Programming.pdf

    61/467Oracle10g: Java Programming 2-11

    Copyright 2004, Oracle. All rights reserved.

    A PC may be

    an object.

    A PC may have a

    CD drive, which

    may be an object.

    A PC may have a

    keyboard, mouse, and

    network card, all of which

    may be objects.

    Defining Object Composition

    Objects can be composed of other objects. Objects can be part of other objects.

    This relationship between objects is known as

    aggregat ion.

    Defining Object CompositionFor example, when you talk about writing or reading from a CD drive, you consider the CD

    drive as a single object. You may also discuss how the CD drive interacts with the personal

    computer system; you treat the computer systems as a single object as well.

    When an engineer is called in to repair a CD drive problem, his or her perspective of a CD drive

    is more detailed. The engineer visualizes the CD drive spindle, the drive tray, and the laser beam

    or reader.

    Each of these are components of the CD drive object, and are objects in their own right. Each of

    these views of the CD drive is equally valid, and each can be expressed at different times.

    When discussing objects, it is useful to use as high a level of abstraction as possible. In this way,you can conceptualize more of the important objects, and understand more about how the system

    works.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    62/467

  • 8/10/2019 Oracle 10g Java Programming.pdf

    63/467Oracle10g: Java Programming 2-13

    Copyright 2004, Oracle. All rights reserved.

    The Donut Diagram

    getAge()

    Client orsender

    Person

    Messagename

    address

    birthdate

    getName

    setBirthdate getAge

    getAddress setAddress

    The Donut DiagramThe donut diagram provides a visible reminder that an object presents an external interface in

    the form of methods and that its instance variables (in this case, name, address, and birthdate) are

    private and hidden inside.

    Client objects interact with this Person object by sending messages to it; that is, by invoking

    its public methods. The client does not know how the getAge method works, nor should the

    client care. There could be an age variable in the place of the calculation based on the birthdate

    variable. Or perhaps this kind of object returns a constant 39.

    Note: This style of diagram has been a very popular one that is useful for conveying concepts.

    However, for real-world projects, it quickly becomes limiting: Real objects could have many

    methods, which would not fit very well. A similar diagram, which ispart of Unified Modeling

    Language (UML), is known as an interaction diagram. An interaction diagram is a generic term

    that applies to several types of diagrams, such as collaboration diagrams, activity diagrams, and

    sequence diagrams. They all represent in different ways where objects are drawn simply as

    circles, and messages among them are drawn as arrows.

    Oracle University provides an inClass course on UML techniques and notation named Object-

    Oriented Analysis and Design using the Unified Modeling Language (UML).

    For further information, refer to http://education.oracle.com.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    64/467Oracle10g: Java Programming 2-14

    Copyright 2004, Oracle. All rights reserved.

    Guided Practice:

    Spot the Operations and Attributes

    Spot the Operations and AttributesFor each graphic, specify at least three attributes and three operations.

    Objects Operations Attributes

    My pencil Write, erase Lead color

    My pen Write, refill Ink color, ink amount

    Jaws Eat, swim Capacity, speed

    Car

    Truck

    Satellite

  • 8/10/2019 Oracle 10g Java Programming.pdf

    65/467Oracle10g: Java Programming 2-15

    Copyright 2004, Oracle. All rights reserved.

    Collaborating Objects

    Collaborating objects work together to complete a taskand form the basis of an application system.

    All methods are defined within a class and are not

    defined globally as in traditional languages.

    All objects are created from classes and contain

    all the attributes and methods of that class.

    Objects must associate with each other to

    collaborate on common tasks.

    Associated objects communicate by sending

    messages.

    A System Is a Collection of Collaborating ObjectsAn object system is made up of a collection of different types of objects. If the system is

    organized to perform some task, then it must ensure that appropriate objects collaborate with

    each other to complete the task. In an object-oriented application, collaboration is necessary

    because all code and data are held in some class or object; there is no concept of global methods

    or variables.

    Objects must first be associated with each other before they can collaborate. After objects are

    associated, communication is done by one object sending a message to another object; that is, the

    sending object must know the recipient of the message. A message is a request to perform part of

    the functionality that is required to support the task.

    The association between objects is achieved dynamically through a reference. (That is, twoclasses may associate with each other, and two objects may have a link between them.) A

    reference forms a link or simply a relationship between the objects. In programming terms, a

    reference can be implemented in various ways. For example, a variable in one object contains areference to the other object. In Java, one way to create an object is to use the new operator.

    Movie m1 = new Movie()

    In this example, the class definition is called Movie that is used as a data type for the variable

    m1. The variable m1 is defined to hold a reference to the new movie object. Another example of

    a link between collaborating objects may be: The customer is the owner of the account, and the

    account is owned by the customer.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    66/467Oracle10g: Java Programming 2-16

    Copyright 2004, Oracle. All rights reserved.

    Objects Interact Through Messages

    Objects communicate by sending messages.

    A sending object must be associated with orlinked to the receiving object.

    The message sender requests the receiver toperform the operation that is named in themessage.

    This communication is similar to calling aprocedure:

    The sender calls a method of the receiver.

    The receiver executes the called method.

    Calling a method is always in the context of aparticular object:myPen.write( ): Object-oriented programming

    write (myPen): Traditional structuredprogramming

    Objects Interact Through MessagesMethods are named blocks of code similar to procedures or functions. The OO terminology

    sending a message indicates that an object communicates with another object by requesting a

    behavior and the associated object is invoked. Before one object can send a message to another,

    the sender must be linked, or associated, with the receiver, via an object reference. Therefore,

    when a message is sent to a receiver, it executes a method in response.

    The receiver responsible for executing the method must have an interface matching the behaviorthat is requested in the message to carry out a particular task or algorithm.

    The process of message-sending is analogous to calling a procedure in a traditional language.

    The sender transfers control to the receiver and resumes execution when the receiver returns

    control. One key difference is that when you call a procedure, the call is bound to a specificpiece of code (some subroutine). For example, using the Pen example in the slide:

    Pen myPen = new Pen(); // get reference to a pen objectmyPen.write(); // Send write() message to myPen

    When you send a message, the specific piece of code that gets executed depends on the class (thetype) of the receiver object. This is required to enable the principle ofpolymorphism, to exist.

    Remember, yousend a message to an object. This notion of a targeted recipient is different fromcalling a procedure.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    67/467Oracle10g: Java Programming 2-17

    Copyright 2004, Oracle. All rights reserved.

    When you create my blue pen, you do not have to

    specify its operations or attributes. You simply

    say what class it belongs to.

    What Is a Class?

    A class is a template for objects. A class definition specifies the operations and

    attributes for all instances of that class.

    A class is used to manage complexity.

    A Class Is a Template for All Objects of That TypeIn an object-oriented application, a class is a specification of all the operations and attributes forthat type of object. When you create a particular object (or instance) of that class, you mustinitialize the attributes and links with specific values. This can be done either when you createthe object or at a later stage by carrying out some operation on the object.

    If you view a class definition as a cookie-cutter, then each class creates cookies (objects) of thesame shape (set of operations, attributes, and links).

    Examples of Classes and Objects

    To describe the characteristics of all pens, you may define a pen class and specify operations,such as write and refill, and attributes, such as ink color and ink remaining. You can then createindividual pen objects to represent my blue pen, teachers red pen, and so on.

    When you create a pen object, you may initialize the ink amount to be full (or empty) andspecify the color of the ink. The write operation for the pen would presumably check the value ofink amount and refuse to write if the pen was empty.

    Classes Are a Natural Way of Describing Similar Objects

    The concept of classes is something that you use every day, without realizing it. For example,when you sat down in this classroom, presumably you sat on a chair. You probably did not carewhich particular chair object you used, as long as the object exhibited all the structure andbehavior of an object belonging to the chair class. The use of chair objects comes naturally toyou after you have grasped the concept of chair, because all chairs exhibit the same propertiesalthough they may each have differing attributes.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    68/467Oracle10g: Java Programming 2-18

    Copyright 2004, Oracle. All rights reserved.

    How Do You Identify a Class?

    Identify the common behavior and structure for agroup of objects.

    Recognize a single coherent concept.

    Caution: A common misconception is the use of

    the words classesand objectsinterchangeably.

    Classes def ineobjects.

    My blue pen ops: write, refill

    attribs: ink amount, color of ink

    Your blue pen ops: write, refill

    attribs: ink amount

    How Do You Classify Objects?The dictionary defines a class as a set, collection, group, or configuration containing members

    having or thought to have at least one attribute in common.

    Most objects in the real world do not have names; you usually identify them by the class that

    they belong to. For example, the large woody leafy thing at the bottom of your garden is usually

    referred to as a tree. The object is the thing at the bottom of your garden, but the class it belongs

    to is tree.

    Object-oriented software development is all about identifying classes and defining what you

    mean by them; that is, Which of all its possible operations, attributes, and links are you

    interested in for our system?

    It is not always as easy as spotting the trees from the woods; sometimes you get many objects

    that do not seem to have much in common, and you have to work at identifying the similarities

    between the objects.

    Classification Is Not Just a Computer Science Concept

    Classification is not a new computer science technique; classification has been going on since

    the time of Plato. Most of the objects in the real world are referred to by using a classification

    system, and you often use different classifications for the same objects depending on your

    current viewpoint.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    69/467

  • 8/10/2019 Oracle 10g Java Programming.pdf

    70/467Oracle10g: Java Programming 2-20

    Comparing Classes and Objects (continued)

    How Many Objects of a Particular Class Exist?

    Some classes may have several objects (or instances) in existence. An example of such a class isString; a typical program contains many String objects at any moment in time.

    Other classes may have only one or two instances. For example, high-level classes such as bank

    and hotel reservation manager typically have only a single instance.

    Note: There need not be any objects of a particular class at any particular point in time. Forexample, if you have a banking system, you will not have any bank account objects until

    someone opens a bank account.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    71/467

  • 8/10/2019 Oracle 10g Java Programming.pdf

    72/467

  • 8/10/2019 Oracle 10g Java Programming.pdf

    73/467Oracle10g: Java Programming 2-23

    Copyright 2004, Oracle. All rights reserved.

    Using the Is-a-Kind-of Relationship

    A subclass objectis-a-kind-of

    superclass

    object.

    A subclass must

    have all the

    attributes and

    behaviors of the

    superclass.

    Savings account

    Account Pen

    Pencil

    A Subclass Object Is-a-Kind-of Superclass ObjectInheritance is often called the is-a-kind-of relationship. This is because an object of the

    subclass is a kind of object of the superclass.

    The Account and Savings account example in the slide can be read as follows: A savings account

    is a kind of account. This is a very important statement; it implies that all operations of the

    superclass also apply to the subclass because each object of the subclass is also an object of the

    superclass.

    The corollary of this is that if an object of the subclass does not have all the operations of the

    superclass, then it should not be a subclass. The Pen and Pencil example in the slide is incorrect

    because the refill operation of the superclass, Pen, does not apply to objects of the subclass.

    Pencil therefore is not a valid subclass of Pen.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    74/467

  • 8/10/2019 Oracle 10g Java Programming.pdf

    75/467

  • 8/10/2019 Oracle 10g Java Programming.pdf

    76/467

  • 8/10/2019 Oracle 10g Java Programming.pdf

    77/467Oracle10g: Java Programming 2-27

    Copyright 2004, Oracle. All rights reserved.

    Engineering for a Black Box Environment

    JavaBeans follow the black box approach whichenables you to:

    Simplify something of arbitrary complexity down

    to a single object that everyone can understand

    Think of large systems as a collection of

    interconnected entities (black boxes)

    communicating via their interfaces

    Leveraging the Black BoxBy thinking of large systems as communication networks by using black boxes, you can see how

    this approach enables you to control the systems complexity by ignoring the details of the

    system that resides in the black box. Then, by organizing the connections between the black

    boxes in a hierarchical way, you can more easily design a system that will be flexible and easy to

    conceptualize.

    JavaBeans is a great example in support of black box engineering. A set of standards is used such

    that everything the designer needs to know about how an object operates is available within the

    class.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    78/467Oracle10g: Java Programming 2-28

    Copyright 2004, Oracle. All rights reserved.

    Order Entry UML Diagram

    UML in Oracle JDeveloper 10gThis diagram of the course classes was created by using JDeveloper.

    The italic class Product is an abstract class, and the lavendar class Taxable is an interface. The

    solid line with an arrow is a Generalization and is used for all dependencies between sub- andsuper-types, and generates an extends statement in the class. A generalization is the

    relationship between a more specific element and a less specific element, and defines the

    inheritance structure in the model. Generalization relationships can be created between two Java

    classes, between two Java interfaces or between two entity objects.

    The dotted line with the arrow represents a Realization, and is used between an interface and aclass, and generates an implements statement in the class. A realization relationship identifies

    which Java class, or classes, implements a Java interface.

    The solid line with no arrow is an association, which signifies a call or a reference from one class

    to another. The type of relationship between OrderItem and Order is composition.

    The Plus (+) next to attributes means that they are public. The - means that they are private.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    79/467Oracle10g: Java Programming 2-29

    Copyright 2004, Oracle. All rights reserved.

    Summary

    In this lesson, you should have learned the following: An object is an abstraction of a real-world object.

    A class is a template or blueprint for objects.

    Classes form inheritance trees: Operations that

    are defined in one class are inherited by all

    subclasses.

    Polymorphism frees the caller from knowing the

    class of the receiving object.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    80/467

  • 8/10/2019 Oracle 10g Java Programming.pdf

    81/467Oracle10g: Java Programming 2-31

    Practice 2: Working with Object-Oriented Principles

    Goal

    The goal of this practice is to become familiar with object-oriented concepts, including classes,

    methods, and attributes. You also learn how to read a UML class model showing the business

    objects for the course application.

    A description of the business rules contains information to enable you to determine the classes,

    methods, attributes, and associations that make up objects in the system. At the end of thepractice, you will have created a design model that includes the major classes in the business.

    The aim is to create a simple UML class model to show these objects.

    Note that a model is a representation of something, and is subject to interpretation. Remember

    that no model is basically wrongbut some models are more usable than others.

    Description of the Order Entry Area of the Business

    The Order Entry component of the business is now becoming automated. In most respects, the

    process of ordering products is rather simple. The customers select the items that they want from

    a list of products. Your customers must be included in your system.You keep information about

    your customers such as name, address, and telephone number. You also assign a unique

    customer ID to each new customer. For customers that are companies, you track a contact person

    and provide for a discount on company purchases. You identify individual customers by their

    license number.

    The order is not very complicated. Each order has a unique number that you can use to keep

    track of it and has information such as the customer who is responsible for the order, the order

    date, shipping mode (air or ground), and an order status. Each order can have multiple line items.

    You currently limit your customers to 10 items per order. Each item on an order has the product

    being purchased, the price, quantity, and the product category. A product category can be a

    composite category consisting of additional categories, or a leaf category.

    You track many things about your products, and the key things include the name, description,and list price. Additionally, you want to include a warranty period, the supplier who distributes

    the product, a catalog URL to reference it on the Web, and a weight classification that is used

    when you calculate shipping costs. It is important for you to also track information about the

    products that are available, and where they are located. You have many warehouses to hold all

    your products.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    82/467Oracle10g: Java Programming 2-32

    Practice 2: Working with Object-Oriented Principles (continued)

    Understanding Object-Oriented Principles

    1. Define the following terms:

    a. Class

    b. Object

    c. Encapsulation

    d. Inheritance

    e. Polymorphism

    Identifying Business Classes, Attributes, and Methods

    2. Identify some of the classes in the Order Entry business, limiting yourself to three. The

    process of identifying a class is to look for nouns that classify a group of things from the

    business description. Some nouns will describe the attributes of a class. Write a simple

    sentence or two describing each class to make sure that it is of interest to the business.

    3. Identify a few attributes for each of the new classes. Remember that attributes may be other

    classes.

    4. Define some behaviors (methods or operations) for each of the classes that you have

    discovered.

    If you have time:

    5. Look for classes that can inherit structure (attributes) and behavior (methods) from other

    classes. Modify your definitions to reflect the inheritance model.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    83/467Oracle10g: Java Programming 2-33

    Copyright 2004, Oracle. All rights reserved.

    Order Entry System

    Partial UML Class Model

    Order

    id: intorderDate: Date

    shipDate: Date

    shipMode: String

    orderTotal: double

    addItem()

    removeItem()

    setOrderDate()

    getOrderDate()

    setShipDate()

    :

    OrderItem

    lineNo: int

    quantity: int

    price: double

    getQuantity()

    setQuantity()

    setPrice()

    getPrice()

    getItemTotal()

    :

    Customer

    name: String

    address: String

    phone: String

    getName()

    setName()

    setAddress()

    getAddress()

    :

    Company

    contact: String

    discount: int

    getContact()

    setContact()

    :

    Individual

    licNumber: String

    setLicNumber()

    getLicNumber()

    :

    Productid: int

    name: String

    description: String

    retailPrice: double

    getPrice()

    :

  • 8/10/2019 Oracle 10g Java Programming.pdf

    84/467

  • 8/10/2019 Oracle 10g Java Programming.pdf

    85/467

    Copyright 2004, Oracle. All rights reserved.

    Basic Java Syntax and Coding

    Conventions

  • 8/10/2019 Oracle 10g Java Programming.pdf

    86/467Oracle10g: Java Programming 3-2

    Copyright 2004, Oracle. All rights reserved.

    Objectives

    After completing this lesson, you should be able to dothe following: Identify the key components of the Java language Identify the three top-level constructs in a Java

    program Identify and describe Java packages Describe basic language syntax and identify Java

    keywords Identify the basic constructs of a Java program Compile and run a Java application Examine the JavaBean architecture as an example

    of standard coding practices Use the CLASSPATH variable and understand its

    importance during compile and run time

    Lesson AimThis lesson introduces the basic constructs of the Java language. You learn conventions,

    standards (that is, capitalization, spacing, and so on), compiling, and running applications.

    You become familiar with the basic language constructs so that you can recognize and

    manipulate them with or without using Oracle JDeveloper. The lesson explores JavaBeans as

    an example of good coding practices.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    87/467Oracle10g: Java Programming 3-3

    Lesson Aim (continued)

    Overview

    Java Components

    The Java environment is made up of a run-time engine, documentation tools, debugging

    utilities, and predefined classes and methods that are designed to decrease development time.

    Conventions

    When programming in Java, you must use established naming, capitalization, indenting, and

    commenting conventions.

    Classes, Objects, and Methods

    In Java, almost everything is an object. Objects are created from blueprints called classes. The

    objects contain attributes (data) that can be accessed by functions that are contained within the

    object. Functions that act on the data are called methods.

    Using Javadoc

    Javadoc is a facility that is provided within J2SE and produces HTML documentation from

    your program. It reads the source code and parses specially formatted and positioned

    comments into documentation.

    Compiling and Running Java

    Java is an interpretive language, which means that the code is interpreted to machine code

    only at run time. This is what makes the write once, run anywhere (WORA) concept work.

    There are several steps in the process of interpreting program source code into a running

    program. Java code is first compiled into bytecodes by the Java compiler. Bytecodes are

    interpretable, intermediate representation of the Java program. The resulting bytecodes are

    interpreted and converted into machine-specific instructions by the Java Virtual Machine

    (JVM) at run time.

    Security Concerns

    Using the jad.exe, you can make the code so confused or opaque as to be difficult to

    perceive or understand. Obfuscation of your code can make field debugging more difficult.

    For example, stack traces are often very useful in isolating bugs. After compression or

    obfuscation by one of these tools, however, the stack trace may no longer contain the original

    method names. In general, refrain from using obfuscation, unless you really want to make it

    difficult to modify your code.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    88/467Oracle10g: Java Programming 3-4

    Copyright 2004, Oracle. All rights reserved.

    Examining Toolkit Components

    The J2SE/J2EE from Sun provides: Compiler

    Bytecode interpreter

    Documentation generator

    J2SE

    Examining Toolkit ComponentsSun J2SE Components

    The Java compiler is javac; it compiles Java source code into Java bytecodes.

    The Java bytecode interpreter is the engine that runs Java applications.

    The program that generates documentation in HTML from Java source code comments

    is javadoc.

    Other J2SE Tools

    jdb : Used as a Java class debugger and it is similar to the dbx or gdb debuggers on

    UNIX jar : Used to create Java Archive (JAR) files, which are zipped Java programs javah : Used to generate C files for native methods javakey : Provides support for generating certification keys for trusted Java code javap : Used to disassemble Java bytecodes into human-readable format native2ascii : Used to convert Java source code to Latin 1 characters

  • 8/10/2019 Oracle 10g Java Programming.pdf

    89/467Oracle10g: Java Programming 3-5

    Copyright 2004, Oracle. All rights reserved.

    Exploring Packages in J2SE/J2EE

    The J2SE/J2EE from Sun provides standard packagesfor:

    Language

    Windowing

    Input/output

    Network communication

    J2SE

    Java PackagesThe Java language includes a series of classes that are organized into packages, depending on

    functional groups. For example, there is a set of classes that helps create and use networkconnections; these classes are contained in the java.netpackage. The basic package forthe Java language is named classes.zip in 1.1.x and is renamed rt.jar since 1.2.x.

    Standard Java Packages

    These packages contain the classes that form the foundation for all Java applications.

    Built-in Classes That Are Distributed with Java Language

    java.lang: Basic language functions

    javax.swing: Parent package to all Swing-related packages java.util: Facility supporting interfacing, implementing, sorting, and searching on

    collections java.awt: Utility to managing layout, handling events, and rendering graphics for

    AWT java.io: General interface for all I/O operations

  • 8/10/2019 Oracle 10g Java Programming.pdf

    90/467Oracle10g: Java Programming 3-6

    Copyright 2004, Oracle. All rights reserved.

    Documenting Using the J2SE

    The J2SE/J2EE from Sun provides documentationsupport for:

    Comments

    Implementation

    Documentation

    Documentation generator

    J2SE

    DocumentationThere are two types of documentation methods in Java that you can specify in your source

    code. One is for the internal documentation, and the other is for external documentation.

    Comments

    Implementation comments are included in the source code. They are useful for

    programmers who are examining the code. When writing implementation comments,

    you must explain the code and any special processes that may need detailed

    explanations. Use:- // to start comments up to the end of the line- /* to start comments across multiple lines, and end with */

    Documentation comments are created using javadoc. Javadoc is a utility that is provided

    with J2SE and that creates an HTML document from the documentation comments in

    Java source code. You can use the javadoc utility to document classes and methods, so

    that they can be better understood when used by other programmers. Use:- /** to start documentation comments across multiple lines, and end with */

    Documentation Generator

    Javadoc is a documentation generator that is part of J2SE.

  • 8/10/2019 Oracle 10g Java Programming.pdf

    91/467Oracle10g: Java Programming 3-7

    Copyright 2004, Oracle. All rights reserved.

    Contents of a Java Source

    A