Oracle10g Java Programming Student Guide - Volume 1.pdf

Embed Size (px)

Citation preview

  • D17249GC11Edition 1.1August 2004D39813

    Oracle10g: Java Programming

    Student Guide - Volume 1

  • 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 GallusGlenn Stokol

    Technical Contributorsand ReviewersKenneth CooperPeter DriverChristian DugasCraig HollisterChika IzumiPete LaseauGlenn MaslenMonica MotleyGayathri Rajagopal

    Publisher

    Poornima G

  • Preface

    I IntroductionObjectives I-2Course Overview I-3

    1 Introducing the Java and Oracle PlatformsObjectives 1-2What Is Java? 1-3Key Benefits of Java 1-4An Object-Oriented Approach 1-6Platform Independence 1-7Using Java with Enterprise Internet Computing 1-8Using the Java Virtual Machine 1-10How Does JVM Work? 1-12Benefits of Just-In-Time (JIT) Compilers 1-14Implementing Security in the Java Environment 1-16Deployment of Java Applications 1-18Using Java with Oracle 10g 1-19Java Software Development Kit 1-20Using the Appropriate Development Kit 1-21Integrated Development Environment 1-22Exploring the JDeveloper Environment 1-23Oracle10g Products 1-24Summary 1-25

    2 Defining Object-Oriented PrinciplesObjectives 2-2What Is Modeling? 2-4What Are Classes and Objects? 2-5An Objects Attributes Maintain Its State 2-6Objects Have Behavior 2-8Objects Are Modeled as Abstractions 2-9Defining Object Composition 2-11The Donut Diagram 2-13Guided Practice: Spot the Operations and Attributes 2-14Collaborating Objects 2-15Objects Interact Through Messages 2-16What Is a Class? 2-17How Do You Identify a Class? 2-18Comparing Classes and Objects 2-19What Is Encapsulation? 2-21What Is Inheritance? 2-22

    Contents

    iii

  • Using the Is-a-Kind-of Relationship 2-23What Is Polymorphism? 2-24Architecture Rules for Reuse 2-26Engineering for a Black Box Environment 2-27Order Entry UML Diagram 2-28Summary 2-29Practice 2: Overview 2-30Order Entry System Partial UML Class Model 2-33

    3 Basic Java Syntax and Coding ConventionsObjectives 3-2Examining Toolkit Components 3-4Exploring Packages in J2SE/J2EE 3-5Documenting Using the J2SE 3-6Contents of a Java Source 3-7Establishing Naming Conventions 3-8More About Naming Conventions 3-10Defining a Class 3-12Rental Class: Example 3-13Creating Code Blocks 3-15Defining Java Methods 3-16Examples of a Method 3-17Declaring Variables 3-18Examples of Variables in the Context of a Method 3-19Rules for Creating Statements 3-20What Are JavaBeans? 3-21Managing Bean Properties 3-22Exposing Properties and Methods 3-23JavaBean Standards at Design Time 3-24Compiling and Running a Java Application 3-25The CLASSPATH Variable 3-26CLASSPATH: Example 3-27Summary 3-28Practice 3: Overview 3-29

    4 Exploring Primitive Data Types and OperatorsObjectives 4-2Reserved Keywords 4-4Variable Types 4-5Primitive Data Types 4-7What Are Variables? 4-9Declaring Variables 4-10Local Variables 4-11Defining Variable Names 4-12What Are Numeric Literals? 4-13What Are Nonnumeric Literals? 4-15

    iv

  • Guided Practice: Declaring Variables 4-17What Are Operators? 4-19Categorizing Operators 4-20Using the Assignment Operator 4-21Working with Arithmetic Operators 4-22More on Arithmetic Operators 4-23Examining Conversions and Casts 4-24Incrementing and Decrementing Values 4-26Relational and Equality Operators 4-27Using the Conditional Operator (?:) 4-28Using Logical Operators 4-29Compound Assignment Operators 4-30Operator Precedence 4-31More on Operator Precedence 4-32Concatenating Strings 4-33Summary 4-34Practice 4: Overview 4-35

    5 Controlling Program FlowObjectives 5-2Categorizing Basic Flow Control Types 5-4Using Flow Control in Java 5-6Using the if Statement 5-7Nesting if Statements 5-8Guided Practice: Spot the Mistakes 5-9Defining the switch Statement 5-10More About the switch Statement 5-12Looping in Java 5-13Using the while Loop 5-14Using the dowhile Loop 5-15Using the for Loop 5-16More About the for Loop 5-17Guided Practice: Spot the Mistakes 5-18The break Statement 5-19Summary 5-20Practice 5: Overview 5-21

    6 Building Applications with Oracle JDeveloper 10gObjectives 6-2What Is Oracle JDeveloper 10g? 6-3Exploring the JDeveloper Environment 6-4Examining Workspaces 6-5What Are Projects? 6-7Creating JDeveloper Items 6-8Creating an Application Workspace 6-9Specifying Project Details 6-10Selecting Additional Libraries 6-11

    v

  • Adding a New J2SE 6-12Looking at the Directory Structure 6-13Exploring the Skeleton Java Application 6-14Finding Methods and Fields 6-15Supporting Code Development with Profiler and Code Coach 6-16Customizing JDeveloper 6-17Using the Help System 6-18Obtaining Help on a Topic 6-19Oracle JDeveloper 10g Debugger 6-20Setting Breakpoints 6-22Using the Debugger Windows 6-24Stepping Through a Program 6-25Watching Data and Variables 6-26Summary 6-27Practice 6: Overview 6-28

    7 Creating Classes and ObjectsObjectives 7-2Using Java Classes 7-4Comparing Classes and Objects 7-5Creating Objects 7-6Using the new Operator 7-7Comparing Primitives and Objects 7-8Using the null Reference 7-9Assigning References 7-10Declaring Instance Variables 7-11Accessing public Instance Variables 7-12Defining Methods 7-13Calling a Method 7-14Specifying Method Arguments: Examples 7-15Returning a Value from a Method 7-16Calling Instance Methods 7-17Applying Encapsulation in Java 7-18Passing Primitives into Methods 7-19Passing Object References into Methods 7-20What Are Class Variables? 7-21Initializing Class Variables 7-22What Are Class Methods? 7-23Guided Practice: Class Methods or Instance Methods 7-24Examples in Java 7-25Creating Classes Using the Class Editor 7-26What Are Java Packages? 7-27Grouping Classes in a Package 7-28

    vi

  • Setting the CLASSPATH with Packages 7-29Access Modifiers 7-30Summary 7-32Practice 7: Overview 7-33

    8 Object Life Cycle and Inner ClassesObjectives 8-2Overloading Methods 8-4Using the this Reference 8-5Initializing Instance Variables 8-6What Are Constructors? 8-7Defining and Overloading Constructors 8-8Sharing Code Between Constructors 8-9final Variables, Methods, and Classes 8-10Reclaiming Memory 8-11Using the finalize() Method 8-12What Are Inner Classes? 8-13Using Member Inner Class 8-14Using Local Inner Class 8-15Defining Anonymous Inner Classes 8-16Using the Calendar Class 8-17Summary 8-18Practice 8: Overview 8-19

    9 Using Strings, String Buffer, Wrapper, and Text-Formatting ClassesObjectives 9-2What Is a String? 9-3Creating a String 9-4Concatenating Strings 9-5Performing Operations on Strings 9-6Performing More Operations on Strings 9-7Comparing String Objects 9-8Producing Strings from Other Objects 9-9Producing Strings from Primitives 9-10Producing Primitives from Strings 9-11Wrapper Class Conversion Methods 9-12Changing the Contents of a String 9-13Formatting Classes 9-14Using the SimpleDateFormat Class 9-15Using the MessageFormat Class 9-16Using DecimalFormat 9-17Guided Practice 9-18Using Regular Expressions 9-20

    vii

  • About System.out.println 9-23About OutputStream and PrintStream 9-24What Is Object Serialization? 9-25Serialization Streams, Interfaces, and Modifiers 9-28Summary 9-29Practice 9: Overview 9-30

    10 Reusing Code with Inheritance and PolymorphismObjectives 10-2Key Object-Oriented Components 10-3Example of Inheritance 10-4Specifying Inheritance in Java 10-5Defining Inheritance by Using Oracle JDeveloper 10g 10-6What Does a Subclass Object Look Like? 10-7Default Initialization 10-8The super Reference 10-9The super Reference Example 10-10Using Superclass Constructors 10-11Specifying Additional Methods 10-13Overriding Superclass Methods 10-15Invoking Superclass Methods 10-17Example of Polymorphism in Java 10-19Treating a Subclass as Its Superclass 10-20Browsing Superclass References by Using Oracle JDeveloper 10g 10-21Acme Video and Polymorphism 10-22Using Polymorphism for Acme Video 10-23Using the instanceof Operator 10-25Limiting Methods and Classes with final 10-26Ensuring Genuine Inheritance 10-27Summary 10-28

    11 Using Arrays and CollectionsObjectives 11-2What Is an Array? 11-3Creating an Array of Primitives 11-4Declaring an Array of Primitives 11-5Creating an Array Object for an Array of Primitives 11-6Initializing Array Elements 11-8Creating an Array of Object References 11-9Initializing the Objects in the Array 11-10Using an Array of Object References 11-11Arrays and Exceptions 11-12Multidimensional Arrays 11-13main() Revisited 11-14

    viii

  • Working with Variable-Length Structures 11-15Modifying a Vector 11-16Accessing a Vector 11-17Java Collections Framework 11-18Collections Framework Components 11-20Using ArrayList and Hashtable 11-21Using Iterators 11-22Summary 11-23Practice 11: Overview 11-24

    12 Structuring Code by Using Abstract Classes and InterfacesObjectives 12-2Defining Abstract Classes 12-3Creating Abstract Classes 12-4What Are Abstract Methods? 12-5Defining Abstract Methods 12-7Defining and Using Interfaces 12-8Examples of Interfaces 12-9Creating Interfaces 12-10Implementing Interfaces 12-12Sort: A Real-World Example 12-13Overview of the Classes 12-14How the Sort Works 12-15The Sortable Interface 12-16The Sort Class 12-17The Movie Class 12-18Using the Sort 12-19Using instanceof with Interfaces 12-20Summary 12-21Practice 12: Overview 12-22

    13 Throwing and Catching ExceptionsObjectives 13-2What Is an Exception? 13-3How Does Java Handle Exceptions? 13-4Advantages of Java Exceptions: Separating Error Handling Code 13-5Advantages of Java Exceptions: Passing Errors Up the Call Stack 13-7Advantages of Java Exceptions: Exceptions Cannot Be Ignored 13-8Checked Exceptions, Unchecked Exceptions, and Errors 13-9What to Do with an Exception 13-11Catching and Handling Exceptions 13-12Catching a Single Exception 13-13Catching Multiple Exceptions 13-14

    ix

  • Cleaning Up with a finally Block 13-15Catching and Handling Exceptions: Guided Practice 13-16Allowing an Exception to Pass to the Calling Method 13-18Throwing Exceptions 13-19Creating Exceptions 13-20Catching an Exception and Throwing a Different Exception 13-21Summary 13-22Practice 13: Overview 13-23

    14 User Interface Design: Swing Basics Planning the Application LayoutObjectives 14-2Running Java UI Applications 14-3AWT, Swing, and JFC 14-4Swing Features 14-6Lightweight or Heavyweight Components? 14-8Planning the UI Layout 14-9The Containment Hierarchy 14-10Top-Level Containers 14-12Intermediate Containers 14-14Atomic Components 14-15Layout Management Overview 14-16Border Layout 14-18GridBag Layout 14-19GridBag Constraints 14-20Using Layout Managers 14-22Combining Layout Managers 14-24Using Frames or Dialogs 14-25Using JPanel Containers 14-27Adding Borders to Components 14-29Using Internal Frames 14-30Swing Text Controls 14-32Adding Components with Oracle JDeveloper 10g 14-33Creating a Frame 14-34Adding Components 14-35Setting Pluggable Look and Feel 14-37Summary 14-39Practice 14: Overview 14-40

    15 Adding User Interface Components and Event HandlingObjectives 15-2Swing Components 15-3Swing Components in JDeveloper 15-5Invoking the UI Editor 15-7How to Add a Component to a Form 15-8Edit the Properties of a Component 15-9Code Generated by JDeveloper 15-10

    x

  • Creating a Menu 15-12Using JDeveloper Menu Editor 15-13Practice 15-1: Overview 15-14UI for Java Application 15-15Java Event Handling Model 15-20Event Handling Code Basics 15-21Event Handling Process: Registration 15-22Event Handling Process: The Event Occurs 15-24Event Handling Process: Running the Event Handler 15-25Using Adapter Classes for Listeners 15-26Swing Model View Controller Architecture 15-27Basic Text Component Methods 15-30Basic JList Component Methods 15-31What Events Can a Component Generate? 15-32How to Define an Event Handler in JDeveloper 15-33Default Event Handling Code Style Generated by JDeveloper 15-34Completing the Event Handler Method 15-35Summary 15-36Practice 15-2: Overview 15-37

    16 Using JDBC to Access the DatabaseObjectives 16-2Java, J2EE, and Oracle 10g 16-3Connecting to a Database with Java 16-4What Is JDBC? 16-5Preparing the Environment 16-6Steps for Using JDBC to Execute SQL Statements 16-8Step 1: Registering the Driver 16-9Connecting to the Database 16-10Oracle JDBC Drivers: Thin Client Driver 16-11Oracle JDBC Drivers: OCI Client Drivers 16-12Choosing the Right Driver 16-13Step 2: Getting a Database Connection 16-14About JDBC URLs 16-15JDBC URLs with Oracle Drivers 16-16Step 3: Creating a Statement 16-17Using the Statement Interface 16-18Step 4a: Executing a Query 16-19The ResultSet Object 16-20Step 4b: Submitting DML Statements 16-21Step 5: Processing the Query Results 16-23Step 6: Closing Connections 16-24A Basic Query Example 16-25

    xi

  • Mapping Database Types to Java Types 16-26Handling an Unknown SQL Statement 16-28Handling Exceptions 16-29Managing Transactions 16-30The PreparedStatement Object 16-31How to Create a PreparedStatement 16-32How to Execute a PreparedStatement 16-33Maximize Database Access 16-34Connection Pooling 16-35Summary 16-38Practice 16: Overview 16-39

    17 Deploying Applications by Using Java Web StartObjectives 17-2What Is Java Web Start? 17-3Running a Web Start Application 17-4Advantages of Web Start 17-5Examining the JNLP File 17-6Deploying Applications with JDeveloper 17-7Creating the Deployment Profile File 17-8Saving the Deployment Profile 17-9Selecting Files to Deploy 17-10Making an Executable .jar File 17-11Creating and Deploying the Archive File 17-12Using JDeveloper to Deploy an Application to Java Web Start 17-13Step 1: Generate Deployment Profiles and Archive Application 17-14Step 2a: Start OC4J 17-15Step 2b: Creating a Connection 17-16Step 3: Use Web Start Wizard to Create a JNLP File 17-17Step 4: Archive and Deploy the Application to the OC4J Server 17-18Summary 17-19Practice 17: Overview 17-20

    Appendix A: Practice Solutions

    Appendix B: Java Language Quick-Reference Guide

    Appendix C: Order Entry Solution

    xii

  • Preface

  • 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 Programming is an instructor-led course featuring lectures and hands-on exercises. Online demonstrations and written practice sessions reinforce the concepts and skills introduced.

  • Preface - 4

    Related Publications

    Oracle PublicationsTitle Part NumberOracle 10g: Build J2EE Applications (inClass course) D17247GC10Oracle JDeveloper 10g: Build Applications with Oracle ADF (inClass course) D16975GC10Oracle JDeveloper Handbook (Oracle Press)

    Additional Publications System release bulletins Installation and users guides Read-me files International Oracle Users Group (IOUG) articles Oracle Magazine

  • 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 notclick 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]

  • Preface - 6

    Typographic Conventions (continued)

    Typographic Conventions In Text (continued)

    Convention Object or Term Example

    Courier New, case sensitive

    Code output, SQL and PL/SQL code elements, Java code elements, directory names, file names, passwords, path names, user input, usernames

    Code output: debug.seti (I,300); SQL code elements: Use the SELECT command to view information stored in the last_name column of the emp table. Java code elements: Java programming involves the String and StringBuffer classes. Directory names: bin (DOS), $FMHOME (UNIX) File names: Locate the init.ora file. Passwords: Use tiger as your password. Path names: Open c:\my_docs\projects. User input: Enter 300. Usernames: Log on as scott.

    Initial cap Graphics labels (unless the term is a proper noun)

    Customer address (but Oracle Payables)

    Italic Emphasized words and phrases in print publications, titles of books and courses, variables

    Do not save changes to the database. For further information, see Oracle7 Server SQL Language Reference Manual. Enter [email protected], where user_id is the name of the user.

    Plus signs Key combinations Press and hold these keys simultaneously: [Control] + [Alt] + [Delete]

    Quotation marks

    Lesson and chapter titles in cross references, interface elements with long names that have only initial caps

    This subject is covered in Unit II, Lesson 3, Working with Objects. Select the Include a reusable module component and click Finish. Use the WHERE clause of query property.

  • Preface - 7

    Typographic Conventions (continued)

    Typographic Conventions in Navigation PathsThis 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

  • Copyright 2004, Oracle. All rights reserved.

    Introduction

  • Oracle10g: Java Programming I-2

    I-2 Copyright 2004, Oracle. All rights reserved.

    Objectives

    After completing this course, you should be able to do the 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

  • Oracle10g: Java Programming I-3

    I-3 Copyright 2004, Oracle. All rights reserved.

    Course Overview

    This course teaches you how to write Java applications.

    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.

  • Copyright 2004, Oracle. All rights reserved.

    Introducing the Javaand Oracle Platforms

  • Oracle10g: Java Programming 1-2

    1-2 Copyright 2004, Oracle. All rights reserved.

    Objectives

    After completing this lesson, you should be able to do the 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.

  • Oracle10g: Java Programming 1-3

    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 MicrosystemsJava is a platform and an object-oriented programming language, which was originally developed by Sun Microsystems, Inc. It was created by James Gosling for use in consumer electronics. Because of the robustness and platform-independent nature of the language, Java soon moved beyond the consumer electronics industry and found a home on the World Wide Web. Java is a platform, which means that it is a complete development and deployment environment.Class LibrariesJava 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, and network communication classes are included in the Java Developers Kit (JDK). The class library makes Java programming significantly easier and faster to develop when compared with other languages. JDK also contains several utilities to facilitate development processes. These utilities handle operations, such as debugging, deployment, and documentation.Java Uses a Virtual MachineOne of the key elements of the Java language is platform independence. A Java program that is written on one platform can be deployed on any other platform. This is usually referred to as write once, run anywhere (WORA). This task is accomplished through the use of the Java Virtual Machine (JVM). JVM runs on a local machine and interprets the Java bytecode and converts it into platform-specific machine code.

  • Oracle10g: Java Programming 1-4

    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-OrientedAn 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 IndependentJava 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.

  • Oracle10g: Java Programming 1-5

    Key Benefits of Java (continued)MultithreadedJava 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 SecureJava has built-in capabilities to prevent memory corruption. Java automatically manages the processes of memory allocation and array bounds checking. It prohibits pointer arithmetic, and restricts objects to named spaces in memory.

  • Oracle10g: Java Programming 1-6

    1-6 Copyright 2004, Oracle. All rights reserved.

    An Object-Oriented Approach

    Objects and classes An object is a run-time representation of a thing. A class is a static definition of things.

    Class models elaborate: Existing classes and objects Behavior, purpose, and structure Relationships between classes Relationships between run-time objects

    Same models exist throughout the project.Analysis Implementation Integrationand testingDesign

    CLASS MODELS

    An Object-Oriented ApproachObject-oriented programming is a powerful and natural paradigm that is used to write application programs. The approach ensures that programs survive the changes accompanying the growth of a business and its systems. After you understand the function of each object and develop clean, reliable interfaces between the functions, you can decommission older parts of an application system without concern.Classes provide a means to capture the structure and behavior of a real-world person, place, or thing, and represent a one-to-one mapping between the real-world object and its implementation. This one-to-one mapping tends to eliminate the typical transformations that are found in nonobject-oriented design approaches.

  • Oracle10g: Java Programming 1-7

    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 LanguageJava program source code is stored in .java files. For example, a Java program dealing with movies in a video rental company may have files called Movie.java, Customer.java, and Rental.java.Each .java file is compiled into a corresponding .class file with the same name. For example, 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 bytecodes into 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 LanguagesWhen compiling a traditional language such as C, the code written by the programmer is converted into machine instructions for the platform on which the compilation takes place. This compiled program can then run only on machines that have the same processor as that on which it was compiled, such as Intel, SPARC, or Alpha.

  • Oracle10g: Java Programming 1-8

    1-8 Copyright 2004, Oracle. All rights reserved.

    Using Java with EnterpriseInternet Computing

    Web server

    Application server

    Presentation Businesslogic

    Servlets JavaServer

    Pages (JSPs)

    EnterpriseJavaBeans (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 TierWhen 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 TierThis 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.

  • Oracle10g: Java Programming 1-9

    Java and Enterprise Internet Computing (continued)Application (Business Logic) TierYou 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 TierThe 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.

  • Oracle10g: Java Programming 1-10

    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.ApplicationsYou 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 the class; 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.

  • Oracle10g: Java Programming 1-11

    Running Java Applications (continued)Running Java AppletsA 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.

  • Oracle10g: Java Programming 1-12

    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 LoaderWhen 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 the local disk or on another system across the network. JVM uses the CLASSPATH 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 VerifierIt 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.

  • Oracle10g: Java Programming 1-13

    How Does JVM Work? (continued)Bytecode InterpreterJVM is the bytecode interpreter that executes the bytecodes for the loaded class. If enabled, JVM can use just-in-time (JIT) technology to translate Java bytecodes into native machine instructions.Memory ManagementJVM keeps track of all instances in use. After an instance is no longer in use, JVM is allowed to release the memory that is used by that object. It performs the release of memory after the object is no longer needed, but not necessarily immediately. The process (thread) that JVM uses to manage dereferenced objects is called garbage collection.

  • Oracle10g: Java Programming 1-14

    1-14 Copyright 2004, Oracle. All rights reserved.

    Benefits of Just-In-Time (JIT) Compilers

    JIT compilers: Improve performance Are useful if the same bytecodes are executed

    repeatedly Translate bytecodes to native instruction Optimize repetitive code, such as loops Use Java HotSpot VM for better performance and

    reliability

    Just-In-Time (JIT) CompilersJVMs translate Java bytecodes into native machine instructions. What happens if the same code is executed again, later in the program? In an environment without JIT compilers, the code is interpreted every time it is encountered, even if it has already been interpreted earlier in the program.The compilers are designed to easily translate bytecode into machine code, which is optimized to run on the target platform.Benefits of Just-In-Time CompilersMost JVMs now support JIT compilation. JIT compilers translate bytecodes only the first time that they are encountered; if the same code is executed later, then it is automatically mapped to the corresponding native machine instruction.JIT compilers enable Java programs to run more quickly because they obviate the need for repeated translation of bytecodes to native machine instructions. This is especially effective in repetitive code, such as loops or recursive functions. Some JIT compilers are intelligent enough to optimize groups of related bytecodes into more efficient native machine instructions.

  • Oracle10g: Java Programming 1-15

    Just-In-Time (JIT) Compilers (continued)Java HotSpotThe Java HotSpot virtual machine (VM) is a key component in maximizing the deployment of enterprise applications. It is a core component of Java 2, Standard Edition (J2SE) software, which is supported by leading application vendors and technologies. Java HotSpot VM supports virtually all aspects of development, deployment, and management of corporate applications.

  • Oracle10g: Java Programming 1-16

    1-16 Copyright 2004, Oracle. All rights reserved.

    Implementing Securityin the Java Environment

    Interface-specific access

    Class loader

    Bytecode verifier

    Language and compiler

    Java Security LayersLanguage and CompilerThe Java language was designed to be a safe language. The constructs that allow direct manipulation of memory pointers have been eliminated, thereby reducing or even eliminating run-time program crashes and, as a consequence, memory leaks.Class LoaderThe class loader ensures that each class coming from a local source (built-ins) and the classes from each network source are stored separately. During execution, the run-time system first looks up the built-ins for referenced classes; if they are not found, then it consults the referencing class. This ensures that built-in classes are not overridden by network-loaded classes. This prevents spoofing, or overriding the expected and trusted behavior of a built-in class. Inside a JVM, there can be several classloaders controlling each applications namespace.

  • Oracle10g: Java Programming 1-17

    Java Security Layers (continued)Bytecode VerifierDuring 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 AccessBuilt-in classes and methods control access to the local file system and network resources. These classes are restrictive by default. If imported code tries to access the local file system, then the security mechanism prompts the user.

  • Oracle10g: Java Programming 1-18

    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 DeploymentJava 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 DeploymentJava applications can also execute on the server machine, as long as a JVM is available on that platform. The use of server-side Java applications is compatible with the multitier model for Internet computing.

  • Oracle10g: Java Programming 1-19

    1-19 Copyright 2004, Oracle. All rights reserved.

    Using Java with Oracle 10g

    Oracledatabase

    Web serverClient

    Application server

    Presentation Businesslogic

    Data

    OracleApplication Server

    Java and Oracle 10gOracle 10g is a complete and integrated platform, which supports all the server-side requirements for Java applications. Oracle 10g comprises the following:Oracle Database 10gIn addition to its database management features, the Oracle Database (currently, version 10g) provides support for a variety of Java-based structures including Java components and Java stored procedures. These Java structures are executed in the database by its built-in Java Virtual Machine, called the Enterprise Java Engine (EJE).Oracle Application Server 10gThe Oracle Application Server 10g maintains and executes all your application logic, including Enterprise JavaBeans, through its own built-in JVM. Oracle Application Server 10g uses the OC4J J2EE server to execute servlets and JSPs. Oracle Application Server 10g Enterprise Manager is the tool that is used to manage and distribute applications, for ease of use.

  • Oracle10g: Java Programming 1-20

    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 LibraryThe 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.

  • Oracle10g: Java Programming 1-21

    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 EditionThe 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 EditionThe 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 EditionThe 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.

  • Oracle10g: Java Programming 1-22

    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 EnvironmentYou 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

  • Oracle10g: Java Programming 1-23

    1-23 Copyright 2004, Oracle. All rights reserved.

    Exploring the JDeveloper Environment

    System Navigator Code Editor Property Inspector

    Component Palette

    The Oracle JDeveloper 10g EnvironmentJDeveloper 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 PaletteProperties 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 NavigatorSystem 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 EditorEditors 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 InspectorProperty Inspector is the window that shows the properties and events associated with a selected component in the design region of a viewer.

  • Oracle10g: Java Programming 1-24

    1-24 Copyright 2004, Oracle. All rights reserved.

    Oracle10g Products

    Oracle 10g ProductsOracle Database 10gThe Oracle Database manages all your information: Word documents, Excel spreadsheets, XML, images, and so on. Oracle Development Suite 10g tools can automatically reuse the database structure and its integrity constraints, which reduces the amount of manual coding.Oracle Application Server 10gThe Oracle Application Server 10g runs 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 10gOracle 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.

  • Oracle10g: Java Programming 1-25

    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.

  • Copyright 2004, Oracle. All rights reserved.

    Defining Object-Oriented Principles

  • Oracle10g: Java Programming 2-2

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

    Objectives

    After completing this lesson, you should be able to do the 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.

  • Oracle10g: Java Programming 2-3

    Overview of Object-Oriented ProgrammingObject-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 long as 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.

  • Oracle10g: Java Programming 2-4

    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 the architect 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.

  • Oracle10g: Java Programming 2-5

    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.

  • Oracle10g: Java Programming 2-6

    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 attribute.

    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.

  • Oracle10g: Java Programming 2-7

    An Objects Attributes Maintain Its State (continued)Typical AttributesAs with operations, different objects store different attributes. For example, the Acme BankATM 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. After you 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.

  • Oracle10g: Java Programming 2-8

    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 operation.

    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 they exist. Object technology decomposes a system entirely into objects; all the interactions between the system and the outside world, and all the internal computations of the system, are carried out by the operations (or methods) of objects.Typical OperationsDifferent objects naturally perform different operations. For example, the Acme Bank ATMobject has operations such as withdraw, print receipt, swipe card, and so on. Alternatively, the my 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 must have an idea about how the object will be used in the system; otherwise, you may end up defining several operations for each object, which is clearly unsatisfactory. It is important to understand how the object will be used in the system and to specify only the operations that are relevant for that mode of usage.You must also ask how the state of the object is changed; that is, How do the values that are held in the object attribute get modified? This question enables you to define operations to maintain the internal details of an object.

  • Oracle10g: Java Programming 2-9

    2-9 Copyright 2004, Oracle. All rights reserved.

    Objects Are Modeled as Abstractions

    A Java object is modeled as an abstract representation 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 not want to model: Attributes: Ink color Operations: Refill, change color, point, write

    Context: Product catalogReal-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). The operations 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 ink color 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 be modeled. When deciding on the attributes and operations for an object, always ask whether they have relevance in the domain of the application; always evaluate the attributes and operations in the application context; that is, Are they required to successfully implement the system to meet business requirements?

  • Oracle10g: Java Programming 2-10

    Objects Are Modeled as Abstractions (continued)Every Object Is UniqueBy definition, each object instance has a unique identity; even if two or more objects have identical states, that is, if their attribute values are the same, the system always treats them as different objects. When you create objects in software, you are given a handle to the object, called an object reference in the Java language. In Java, this handle or object reference is given a name by which it can refer to the object.

  • Oracle10g: Java Programming 2-11

    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

    aggregation.

    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.

  • Oracle10g: Java Programming 2-12

    Defining Object Composition (continued)AggregationThis concept of objects being composed of many subobjects is known as aggregation.When you break a big object down into several low-level objects, these low-level objects can often be reused in subsequent projects. For example, ATMs use keypads, but so do cash registers, telephones, and television remote controls.Note: An aggregation is a special type (closely coupled) of association known as a composition. To make a distinction, think of an association as a collaborates with relationship. Think of an aggregation as a made of or composed of relationshipfor example, an account is made of transactions, whereas an order is made of order lines. There are two types of aggregation, strong and weak. Strong aggregation is also called composition. Both are implemented by using references in Java.

  • Oracle10g: Java Programming 2-13

    2-13 Copyright 2004, Oracle. All rights reserved.

    The Donut Diagram

    getAge()

    Client orsender

    Person

    Messagenameaddressbirthdate

    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 is part 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.

  • Oracle10g: Java Programming 2-14

    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

  • Oracle10g: Java Programming 2-15

    2-15 Copyright 2004, Oracle. All rights reserved.

    Collaborating Objects

    Collaborating objects work together to complete a task and 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, two classes 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 a reference 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.

  • Oracle10g: Java Programming 2-16

    2-16 Copyright 2004, Oracle. All rights reserved.

    Objects Interact Through Messages

    Objects communicate by sending messages. A sending object must be associated with or

    linked to the receiving object. The message sender requests the receiver to

    perform the operation that is named in the message.

    This communication is similar to calling a procedure: The sender calls a method of the receiver. The receiver executes the called method.

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

    programming

    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 behavior that 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 specific piece 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 (the type) of the receiver object. This is required to enable the principle of polymorphism, to exist.Remember, you send a message to an object. This notion of a targeted recipient is different from calling a procedure.

  • Oracle10g: Java Programming 2-17

    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 for that type of object. When you create a particular object (or instance) of that class, you must initialize the attributes and links with specific values. This can be done either when you create the 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 the same shape (set of operations, attributes, and links).Examples of Classes and ObjectsTo 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 create individual 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) and specify the color of the ink. The write operation for the pen would presumably check the value of ink amount and refuse to write if the pen was empty.Classes Are a Natural Way of Describing Similar ObjectsThe 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 care which particular chair object you used, as long as the object exhibited all the structure and behavior of an object belonging to the chair class. The use of chair objects comes naturally to you after you have grasped the concept of chair, because all chairs exhibit the same properties although they may each have differing attributes.

  • Oracle10g: Java Programming 2-18

    2-18 Copyright 2004, Oracle. All rights reserved.

    How Do You Identify a Class?

    Identify the common behavior and structure for a group of objects.

    Recognize a single coherent concept. Caution: A common misconception is the use of

    the words classes and objects interchangeably. Classes define objects.

    My blue pen ops: write, refillattribs: ink amount, color of ink

    Your blue pen ops: write, refillattribs: 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 ConceptClassification 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.

  • Oracle10g: Java Programming 2-19

    2-19 Copyright 2004, Oracle. All rights reserved.

    Comparing Classes and Objects

    Classes are static definitions that you can use to understand all the objects of that class.

    Objects are the dynamic entities that exist in the real world and your simulation of it.

    Caution: OO people almost always use the words classes and objects interchangeably; you must understand the context to differentiate between the two meanings.

    Comparing Classes and ObjectsObjects exist only at run time; they hold attribute values, provide operations to be executed, and communicate by sending messages to each other. There can be many instances of a particular type of object.Classes are loaded into the run-time environment and used as a template to create the object instances, similar to a cookie-cutter. Although they are static definitions, they must be available at run time to be able to manufacture objects with all the qualities (for example, structure and function) defined in the class.A loose analogy from a purely structural perspective: A database table is a definition of a row; that is, the table structure can be loosely thought of as a class definition, and each row holds specific values as a separate instance with a structure that is defined by the table (the class). Both the table definition and its rows must exist in the database. There are many rows, but only one table definition.

  • Oracle10g: 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 is String; 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. For example, if you have a banking system, you will not have any bank account objects until someone opens a bank account.

  • Oracle10g: Java Programming 2-21

    2-21 Copyright 2004, Oracle. All rights reserved.

    What Is Encapsulation?

    Encapsulation hides the internal structure and operations of an object behind an interface. A bank ATM is an object that gives its users cash.

    The ATM hides (encapsulates) the actual operation of withdrawal from the user.

    The interface (way to operate the ATM) is provided by the keyboard functions, screen, cash dispenser, and so on.

    Bypassing the encapsulation is bank robbery. Bypassing encapsulation in object-oriented

    programming is impossible.

    The Benefits of EncapsulationWith encapsulation, the developer can use an object and ignore the low-level details about how the object is structured and how it works internally. This frees the developer to think at a higher level of abstraction.This results in the ability to comprehend more objects, and to understand more complex systems.Comparing this with real life, if you had to understand how things worked before being able to use them, then you would not be able to deal with real-life objects such as ATMs, airplanes, microwave ovens, computers, or video recorders. To use these things, you deal with them by using their interfaces and ignoring their implementations.An added benefit is that the implementation of the operations may change, and you should still be able to use them in the usual manner.Think again about the ATM. If the bank rewrites the software or changes the hardware of the ATM, then it does not have to inform everyone how to use the new system. This is because the interface has not changed; you still use the ATM in the same manner. When you see minor changes to the interface of the ATM, it probably means that the software behind it has been completely rewritten.In software terms, encapsulation is a mechanism to hide information and functionality, and it enforces security to control access to internal data and functionality. Programming rules prevent the encapsulation of an object from being violated.

  • Oracle10g: Java Programming 2-22

    2-22 Copyright 2004, Oracle. All rights reserved.

    What Is Inheritance?

    There may be a commonality between different classes.

    Define the common properties in a superclass.

    The subclasses use inheritance to include those properties.

    Savings account Checking accountAccount

    Inheritance Is a Relationship Between ClassesInheritance is a relationship between classes, where one class declares another as its parent. When an object of the child class is created, it inherits all the properties of the parent class in addition to those defined in the child class itself. The child class can provide additional attributes and behavior that are relevant to it and can also redefine operations that are specified in the parent class if a different implementation is required.Inheritance Clarifies Your DesignThe use of classes to divide the world into a relatively small number of types is intuitive because humans naturally think that way. However, the model of the world is not flat. When you define two classes, you may notice that the classes share a lot of common attributes and operations. For example, imagine that you are implementing an air-traffic control system, and you define an airplane class and a helicopter class; these two classes have certain characteristics in common, and it makes sense to factor the common features into a parent class called aircraft. The airplane and helicopter classes can then inherit from aircraft; all you must specify in these classes is how they differ from the aircraft class.Inheritance Also Improves ProductivityAs well as improving the clarity of your design, inheritance can also improve productivity because new classes can be created quickly, based on existing classes. Where a class exists, but does not quite meet your needs, the original class need not be modified at all; instead, a new subclass can be defined, and the differences can be specified in this new class.

  • Oracle10g: Java Programming 2-23

    2-23 Copyright 2004, Oracle. All rights reserved.

    Using the Is-a-Kind-of Relationship

    A subclass object is-a-kind-ofsuperclass 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.

  • Oracle10g: Java Programming 2-24

    2-24 Copyright 2004, Oracle. All rights reserved.

    What Is Polymorphism?

    Polymorphism refers to: Many forms of the same operation The ability to request an operation with the same

    meaning to different objects. However, each object implements the operation in a unique way.

    The principles of inheritance and object substitution.

    Load passengers

    What Is Polymorphism?Polymorphism (Greek for many forms), as applied to object technology, means that the same operation can be defined for different classes, and each can implement it in its own way. The implementation of an operation is called a method, and so polymorphism means that there may be many ways to implement methods for one operation. In the example in the slide, there is one operation to load passengers, but each class has a different method to implement the operation.Why Is Polymorphism Important?The importance of polymorphism is that the load passengers operation can be invoked on an object of any of the three classes, and the correct method is called automatically. This frees the caller from interrogating the object to determine its precise class. Polymorphism requires that an object can send the same or a common message to different objects, allowing the different objects to respond in their own way.Another example: If you have a superclass InventoryItem and Movie, VCR, Toys, and so on as subclasses, you can easily extend the store with new goods by subclassing from InventoryItem. The developer creating the OrderEntry application gets an array of InventoryItems and only knows about the API of this class. By calling abstract methods getDescription() and getPrice(), he or she will be able to render the Order page without any detailed knowledge of all the subclasses.

  • Oracle10g: Java Programming 2-25

    What Is Polymorphism? (continued)Each Polymorphic Method Must Have the Same Logical BehaviorThere is a small price to pay for the benefits of polymorphism. Each object implementing the load passengers operation must have the same semantics. For example, if you define a load passengers method for a cruise ship such that it means get the passengers drunk, then this is not polymorphic in meaning with other methods that may mean get the passengers aboard.Polymorphic Methods Must Have the Same SignaturePolymorphic methods must have the same signature; in other words, the arguments that are passed into the method, and the value that is returned, must be consistent in all the polymorphic methods.

  • Oracle10g: Java Programming 2-26

    2-26 Copyright 2004, Oracle. All rights reserved.

    Architecture Rules for Reuse

    Write code that contains: Events that can interact with your Java application Properties that can be exposed Methods that can be invoked

    Write code that supports: Introspection or reflection Customization Persistence

    Using a Standard ProtocolGood Java code must adhere to standards. JavaBeans are an example of the type of standards you can incorporate into your code. A JavaBean is simply a Java class that obeys a strict protocol and usually consists of a group of support classes and resource files, which are packaged into an archive file. Consider a JavaBean as a black box, where all you need to know is the functionality of the box, and not the functionality of its contents. Individual JavaBeans will vary in the functionality that they support, but the typical features of the unifying architecture that distinguish a JavaBean are support for:

    Events, as a simple communication metaphor than can be used to connect beans Properties, both for customization and for programmatic use Public methods to be fired by an event Introspection and reflection, so that at design time, a builder tool can analyze how a bean

    works. Introspection and reflection enable a Java class to dynamically determine the basic structure of the bean through its public interface definitions. This depends on the bean having been written by using a structured coding pattern.

    Customization, so that when using an application builder a user can customize the appearance and behavior of a bean

    Persistence, so that a bean can be customized in an application builder and then have the state of its customized objects saved and reloaded later, using serialization

  • Oracle10g: Java Programming 2-27

    2-27 Copyright 2004, Oracle. All rights reserved.

    Engineering for a Black Box Environment

    JavaBeans follow the black box approach which enables 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.

  • Oracle10g: Java Programming 2-28

    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. Thesolid line with an arrow is a Generalization and is used for all dependencies between sub- and super-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 a class, 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.

  • Oracle10g: Java Programming 2-29

    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.

  • Oracle10g: Java Programming 2-30

    2-30 Copyright 2004, Oracle. All rights reserved.

    Practice 2: Overview

    This practice covers: Identifying business objects for the Order Entry

    system Identifying methods for the classes Identifying attributes for the classes Searching for inheritance in the classes Examining UML class model for course

    application

  • Oracle10g: Java Programming 2-31

    Practice 2: Working with Object-Oriented PrinciplesGoalThe 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 the practice, 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 th