oracle10g java programming instructor guide - volume 1.pdf
TRANSCRIPT
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
1/329
D17249GC11
Edition 1.1
August 2004
D39815
Oracle10g: Java Programming
Instructor Guide - Volume 1
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
2/329
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
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
3/329
Preface
I Introduction
Objectives I-2
Course Overview I-3
1 Introducing the Java and Oracle Platforms
Objectives 1-2
What Is Java? 1-3
Key Benefits of Java 1-4
An Object-Oriented Approach 1-6
Platform Independence 1-7
Using Java with Enterprise Internet Computing 1-8
Using the Java Virtual Machine 1-10
How Does JVM Work? 1-12
Benefits of Just-In-Time (JIT) Compilers 1-14
Implementing Security in the Java Environment 1-16
Deployment of Java Applications 1-18
Using Java with Oracle 10g 1-19
Java Software Development Kit 1-20
Using the Appropriate Development Kit 1-21
Integrated Development Environment 1-22
Exploring the JDeveloper Environment 1-23
Oracle10g Products 1-24
Summary 1-25
2 Defining Object-Oriented Principles
Objectives 2-2
What Is Modeling? 2-4
What Are Classes and Objects? 2-5
An 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
ii i
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
4/329
Using the Is-a-Kind-of Relationship 2-23
What Is Polymorphism? 2-24
Architecture Rules for Reuse 2-26
Engineering for a Black Box Environment 2-27
Order Entry UML Diagram 2-28
Summary 2-29
Practice 2: Overview 2-30Order Entry System Partial UML Class Model 2-33
3 Basic Java Syntax and Coding Conventions
Objectives 3-2
Examining Toolkit Components 3-4
Exploring Packages in J2SE/J2EE 3-5
Documenting Using the J2SE 3-6
Contents of a Java Source 3-7
Establishing Naming Conventions 3-8
More About Naming Conventions 3-10
Defining a Class 3-12Rental Class: Example 3-13
Creating Code Blocks 3-15
Defining Java Methods 3-16
Examples of a Method 3-17
Declaring Variables 3-18
Examples of Variables in the Context of a Method 3-19
Rules for Creating Statements 3-20
What Are JavaBeans? 3-21
Managing Bean Properties 3-22
Exposing Properties and Methods 3-23JavaBean Standards at Design Time 3-24
Compiling and Running a Java Application 3-25
The CLASSPATHVariable 3-26
CLASSPATH: Example 3-27
Summary 3-28
Practice 3: Overview 3-29
4 Exploring Primitive Data Types and Operators
Objectives 4-2
Reserved Keywords 4-4
Variable Types 4-5Primitive Data Types 4-7
What Are Variables? 4-9
Declaring Variables 4-10
Local Variables 4-11
Defining Variable Names 4-12
What Are Numeric Literals? 4-13
What Are Nonnumeric Literals? 4-15
iv
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
5/329
Guided Practice: Declaring Variables 4-17
What Are Operators? 4-19
Categorizing Operators 4-20
Using the Assignment Operator 4-21
Working with Arithmetic Operators 4-22
More on Arithmetic Operators 4-23
Examining Conversions and Casts 4-24Incrementing and Decrementing Values 4-26
Relational and Equality Operators 4-27
Using the Conditional Operator (?:) 4-28
Using Logical Operators 4-29
Compound Assignment Operators 4-30
Operator Precedence 4-31
More on Operator Precedence 4-32
Concatenating Strings 4-33
Summary 4-34
Practice 4: Overview 4-35
5 Controlling Program Flow
Objectives 5-2
Categorizing Basic Flow Control Types 5-4
Using Flow Control in Java 5-6
Using the i f Statement 5-7
Nesting i f Statements 5-8
Guided Practice: Spot the Mistakes 5-9
Defining the swi t ch Statement 5-10
More About the swi t ch Statement 5-12
Looping in Java 5-13Using the whi l e Loop 5-14
Using the dowhi l e Loop 5-15
Using the f or Loop 5-16
More About the f or Loop 5-17
Guided Practice: Spot the Mistakes 5-18
The br eak Statement 5-19
Summary 5-20
Practice 5: Overview 5-21
6 Building Applications with Oracle JDeveloper 10g
Objectives 6-2What Is Oracle JDeveloper 10g? 6-3
Exploring the JDeveloper Environment 6-4
Examining Workspaces 6-5
What Are Projects? 6-7
Creating JDeveloper Items 6-8
Creating an Application Workspace 6-9
Specifying Project Details 6-10
Selecting Additional Libraries 6-11
v
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
6/329
Adding a New J2SE 6-12
Looking at the Directory Structure 6-13
Exploring the Skeleton Java Application 6-14
Finding Methods and Fields 6-15
Supporting Code Development with Profiler and Code Coach 6-16
Customizing JDeveloper 6-17
Using the Help System 6-18Obtaining Help on a Topic 6-19
Oracle JDeveloper 10g Debugger 6-20
Setting Breakpoints 6-22
Using the Debugger Windows 6-24
Stepping Through a Program 6-25
Watching Data and Variables 6-26
Summary 6-27
Practice 6: Overview 6-28
7 Creating Classes and Objects
Objectives 7-2Using Java Classes 7-4
Comparing Classes and Objects 7-5
Creating Objects 7-6
Using the newOperator 7-7
Comparing Primitives and Objects 7-8
Using the nul l Reference 7-9
Assigning References 7-10
Declaring Instance Variables 7-11
Accessing publ i c Instance Variables 7-12
Defining Methods 7-13Calling a Method 7-14
Specifying Method Arguments: Examples 7-15
Returning a Value from a Method 7-16
Calling Instance Methods 7-17
Applying Encapsulation in Java 7-18
Passing Primitives into Methods 7-19
Passing Object References into Methods 7-20
What Are Class Variables? 7-21
Initializing Class Variables 7-22
What Are Class Methods? 7-23
Guided Practice: Class Methods or Instance Methods 7-24
Examples in Java 7-25
Creating Classes Using the Class Editor 7-26
What Are Java Packages? 7-27
Grouping Classes in a Package 7-28
vi
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
7/329
Setting the CLASSPATHwith Packages 7-29
Access Modifiers 7-30
Summary 7-32
Practice 7: Overview 7-33
8 Object Life Cycle and Inner Classes
Objectives 8-2
Overloading Methods 8-4
Using the t hi s Reference 8-5
Initializing Instance Variables 8-6
What Are Constructors? 8-7
Defining and Overloading Constructors 8-8
Sharing Code Between Constructors 8-9
f i nal Variables, Methods, and Classes 8-10
Reclaiming Memory 8-11
Using the f i nal i ze( ) Method 8-12
What Are Inner Classes? 8-13
Using Member Inner Class 8-14Using Local Inner Class 8-15
Defining Anonymous Inner Classes 8-16
Using the Cal endar Class 8-17
Summary 8-18
Practice 8: Overview 8-19
9 Using Strings, String Buffer, Wrapper, and Text-Formatting Classes
Objectives 9-2
What Is a St r i ng? 9-3
Creating a St r i ng 9-4
Concatenating Strings 9-5
Performing Operations on Strings 9-6
Performing More Operations on Strings 9-7
Comparing St r i ng Objects 9-8
Producing Strings from Other Objects 9-9
Producing Strings from Primitives 9-10
Producing Primitives from Strings 9-11
Wrapper Class Conversion Methods 9-12
Changing the Contents of a String 9-13
Formatting Classes 9-14
Using the Si mpl eDat eFor mat Class 9-15Using the Mes sageFor mat Class 9-16
Using Deci mal For mat 9-17
Guided Practice 9-18
Using Regular Expressions 9-20
vii
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
8/329
About Syst em. out . pr i nt l n 9-23
About Out put St r eamand Pr i nt St r eam 9-24
What Is Object Serialization? 9-25
Serialization Streams, Interfaces, and Modifiers 9-28
Summary 9-29
Practice 9: Overview 9-30
10 Reusing Code with Inheritance and Polymorphism
Objectives 10-2
Key Object-Oriented Components 10-3
Example of Inheritance 10-4
Specifying Inheritance in Java 10-5
Defining Inheritance by Using Oracle JDeveloper 10g 10-6
What Does a Subclass Object Look Like? 10-7
Default Initialization 10-8
The super Reference 10-9
The super Reference Example 10-10
Using Superclass Constructors 10-11Specifying Additional Methods 10-13
Overriding Superclass Methods 10-15
Invoking Superclass Methods 10-17
Example of Polymorphism in Java 10-19
Treating a Subclass as Its Superclass 10-20
Browsing Superclass References by Using Oracle JDeveloper 10g 10-21
Acme Video and Polymorphism 10-22
Using Polymorphism for Acme Video 10-23
Using the i nst anceof Operator 10-25
Limiting Methods and Classes with f i nal 10-26Ensuring Genuine Inheritance 10-27
Summary 10-28
11 Using Arrays and Collections
Objectives 11-2
What Is an Array? 11-3
Creating an Array of Primitives 11-4
Declaring an Array of Primitives 11-5
Creating an Array Object for an Array of Primitives 11-6
Initializing Array Elements 11-8
Creating an Array of Obj ect References 11-9Initializing the Objects in the Array 11-10
Using an Array of Obj ect References 11-11
Arrays and Exceptions 11-12
Multidimensional Arrays 11-13
mai n( ) Revisited 11-14
viii
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
9/329
Working with Variable-Length Structures 11-15
Modifying a Vector 11-16
Accessing a Vector 11-17
Java Collections Framework 11-18
Collections Framework Components 11-20
Using Ar r ayLi st and Hasht abl e 11-21
Using I t er at or s 11-22Summary 11-23
Practice 11: Overview 11-24
12 Structuring Code by Using Abstract Classes and Interfaces
Objectives 12-2
Defining Abstract Classes 12-3
Creating Abstract Classes 12-4
What Are Abstract Methods? 12-5
Defining Abstract Methods 12-7
Defining and Using Interfaces 12-8
Examples of Interfaces 12-9Creating Interfaces 12-10
Implementing Interfaces 12-12
Sort: A Real-World Example 12-13
Overview of the Classes 12-14
How the Sort Works 12-15
The Sor t abl e Interface 12-16
The Sor t Class 12-17
The Movi e Class 12-18
Using the Sort 12-19
Using i nst anceof with Interfaces 12-20Summary 12-21
Practice 12: Overview 12-22
13 Throwing and Catching Exceptions
Objectives 13-2
What Is an Exception? 13-3
How Does Java Handle Exceptions? 13-4
Advantages of Java Exceptions: Separating Error Handling Code 13-5
Advantages of Java Exceptions: Passing Errors Up the Call Stack 13-7
Advantages of Java Exceptions: Exceptions Cannot Be Ignored 13-8
Checked Exceptions, Unchecked Exceptions, and Errors 13-9What to Do with an Exception 13-11
Catching and Handling Exceptions 13-12
Catching a Single Exception 13-13
Catching Multiple Exceptions 13-14
ix
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
10/329
Cleaning Up with a f i nal l y Block 13-15
Catching and Handling Exceptions: Guided Practice 13-16
Allowing an Exception to Pass to the Calling Method 13-18
Throwing Exceptions 13-19
Creating Exceptions 13-20
Catching an Exception and Throwing a Different Exception 13-21
Summary 13-22Practice 13: Overview 13-23
14 User Interface Design: Swing Basics Planning the Application Layout
Objectives 14-2
Running Java UI Applications 14-3
AWT, Swing, and JFC 14-4
Swing Features 14-6
Lightweight or Heavyweight Components? 14-8
Planning the UI Layout 14-9
The Containment Hierarchy 14-10
Top-Level Containers 14-12Intermediate Containers 14-14
Atomic Components 14-15
Layout Management Overview 14-16
Border Layout 14-18
GridBag Layout 14-19
GridBag Constraints 14-20
Using Layout Managers 14-22
Combining Layout Managers 14-24
Using Frames or Dialogs 14-25
Using J Panel Containers 14-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
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
11/329
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
12/329
Mapping Database Types to Java Types 16-26
Handling an Unknown SQL Statement 16-28
Handling Exceptions 16-29
Managing Transactions 16-30
The Pr epar edSt at ement Object 16-31
How to Create a Pr epar edSt at ement 16-32
How to Execute a Pr epar edSt at ement 16-33Maximize Database Access 16-34
Connection Pooling 16-35
Summary 16-38
Practice 16: Overview 16-39
17 Deploying Appl ications by Using Java Web Start
Objectives 17-2
What Is Java Web Start? 17-3
Running a Web Start Application 17-4
Advantages of Web Start 17-5
Examining the JNLP File 17-6Deploying Applications with JDeveloper 17-7
Creating the Deployment Profile File 17-8
Saving the Deployment Profile 17-9
Selecting Files to Deploy 17-10
Making an Executable . j ar File 17-11
Creating and Deploying the Archive File 17-12
Using JDeveloper to Deploy an Application to Java Web Start 17-13
Step 1: Generate Deployment Profiles and Archive Application 17-14
Step 2a: Start OC4J 17-15
Step 2b: Creating a Connection 17-16
Step 3: Use Web Start Wizard to Create a JNLP File 17-17
Step 4: Archive and Deploy the Application to the OC4J Server 17-18
Summary 17-19
Practice 17: Overview 17-20
Appendix A: Practice Solu tions
Appendix B: Java Language Quick-Reference Guide
Appendix C: Order Ent ry Solut ion
xi i
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
13/329
Preface
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
14/329
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
15/329
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 Organized
Oracle 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.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
16/329
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
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
17/329
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]
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
18/329
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. set i ( I , 300) ;
SQL code elements: Use the SELECTcommand to view
information stored in the l ast _namecolumn of the emptable.
Java code elements: Java programming involves the
St r i ngand St r i ngBuf f er classes.
Directory names: bi n(DOS), $FMHOME(UNIX)
File names: Locate the i ni t . or afile.
Passwords: Use t i ger as your password.
Path names: Open c: \ my_docs\ pr oj ect s .
User input: Enter 300.
Usernames: Log on as scott .
Initial cap Graphics labels
(unless the term is a
proper noun)
Customer address (butOracle Payables)
Italic Emphasized words
and phrases in print
publications, titles
of books and
courses, variables
Do notsave changes to the database.
For further information, see Oracle7 Server SQL
Language Reference Manual.
Enter [email protected], where user_idisthe 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 WHEREclause of query property.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
19/329
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
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
20/329
Copyright 2004, Oracle. All rights reserved.
Introduction
Schedule: Timing Topic
10 minutes Lecture
10 minutes Total
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
21/329Oracle10g: Java Programming I-2
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
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
22/329Oracle10g: Java Programming I-3
I-3 Copyright 2004, Oracle. All rights reserved.
Course Overview
This course teaches you how to write Javaapplications.
You also learn how to bui ld, debug, and deploy
applications by using Oracle JDeveloper 10g.
The development environment is Oracle
JDeveloper 10g and the Oracle Database.
Instructor Note
The database used for this course is 9.2. It is the latest edition supported by the Development
Tools.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
23/329
Copyright 2004, Oracle. All rights reserved.
Introducing the Java
and Oracle Platforms
Schedule: Timing Topic
60 minutes Lecture
00 minutes Practice
60 minutes Total
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
24/329
Oracle10 : Java Pro rammin 1-2
1-2 Copyright 2004, Oracle. All rights reserved.
Objectives
After completing this lesson, you should be able to dothe following:
Identi fy the key elements of Java
Describe the Java Virtual Machine (JVM)
Examine how Java is used to build applications
Identi fy the key components of the J2SE Java
Development Kit (known as JDK or SDK)
Describe Java deployment options
Lesson Aim
This 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.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
25/329
Oracle10 : Java Pro rammin 1-3
1-3 Copyright 2004, Oracle. All rights reserved.
What Is Java?
Java: Is a platform and an object-oriented language
Was or iginally 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 LibrariesJava contains a broad set of predefined classes, which contain attributes and methods that handlemost 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 as
write 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.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
26/329
Oracle10 : Java Pro rammin 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 Java
Object-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 Distributed
Java classes can be downloaded dynamically over the network when required. In addition, Java
provides extensive support for client-server and distributed programming.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
27/329
Oracle10 : Java Pro rammin 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, and
restricts objects to named spaces in memory.
Instructor Note
Historically speaking, Goslings team started using C++ initially, but soon found that C++programs were too liable to crash, partly due to language complexity, and also because of thedestructive capabilities of C++ constructs, such as pointers. To overcome these problems,Goslings team invented their own object-oriented language, called Oak. To make it robust, theyeliminated problematic language constructs, and made it architecturally neutral, by fullyspecifying the semantics of the language and creating a virtual machine to execute the programs.Oak was designed from the ground up to look like C++ but also to reduce the learning curve forthose who knew C++. Oak was renamed Java, when it gained popularity in the World Wide Weband the revolution began. The robustness, compactness, platform independence, and flexibilitythat had been designed for the electronics consumer market make Java the ideal language forcreating Web-based programs. Because Java is an interpreted language, it is slower than C++ interms of execution speed, but this is often unimportant when dealing with user interactions.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
28/329
Oracle10 : Java Pro rammin 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 c lass is a static definit ion 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 ImplementationIntegrationand testing
Design
CLASS MODELS
An Object-Oriented Approach
Object-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 innonobject-oriented design approaches.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
29/329
Oracle10 : Java Pro rammin 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 t ime.
The Java .class file is the executable code.
Compile
Movie.java
JVM
Running programMovie.class
(javac) (java)
Platform Independence
Java Is an Interpreted Language
Java program source code is stored in . j ava files. For example, a Java program dealing withmovies in a video rental company may have files calledMovi e. j ava, Cust omer . j ava, andRent al . j ava.
Each . j ava file is compiled into a corresponding . cl ass file with the same name. Forexample, a Movi e. j ava compiles to at least one class file. (Inner classes is quite common.)But, the public Movi e. j ava compiles to one Movi e. cl ass. These. cl ass 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 . cl ass 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. This
compiled program can then run only on machines that have the same processor as that on whichit was compiled, such as Intel, SPARC, or Alpha.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
30/329
Oracle10 : Java Pro rammin 1-8
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 Computing
You 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.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
31/329
Oracle10 : Java Pro rammin 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.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
32/329
Oracle10 : Java Pro rammin 1-10
1-10 Copyright 2004, Oracle. All rights reserved.
Using the Java Virtual Machine
Operating system
JVM
Applicat ion
Running Java Applications
All 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 mai n( . . . ) . JVM runs the code by interpreting the
bytecodes in the Java program and converting bytecode into platform-specific machineinstructions.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
33/329
Oracle10 : Java Pro rammin 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.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
34/329
Oracle10 : Java Pro rammin 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 f iles.
JVM Verif ier checks for i llegal 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 col lection.
How Does JVM Work?
JVM Class Loader
When a . cl ass 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 theCLASSPATHenvironmentvariable to determine the location of local . cl ass files. The classpath can be added in run timeby using thej ava - cp or - cl asspat h 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.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
35/329
Oracle10 : Java Pro rammin 1-13
How Does JVM Work? (continued)
Bytecode Interpreter
JVM 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 Management
JVM 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.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
36/329
Oracle10 : Java Pro rammin 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) Compilers
JVMs 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 Compilers
Most 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.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
37/329
Oracle10 : Java Pro rammin 1-15
Just-In-Time (JIT) Compilers (continued)
Java HotSpot
The 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.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
38/329
Oracle10 : Java Pro rammin 1-16
1-16 Copyright 2004, Oracle. All rights reserved.
Implementing Security
in the Java Environment
Interface-specific access
Class loader
Bytecode verifier
Language and compiler
Java Security Layers
Language and Compiler
The 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 Loader
The 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.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
39/329
Oracle10 : Java Pro rammin 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.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
40/329
Oracle10 : Java Pro rammin 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 multit ier model for Internet
computing.
Java Applications
Java 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 that
platform. The use of server-side Java applications is compatible with the multitier model for
Internet computing.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
41/329
Oracle10 : Java Pro rammin 1-19
1-19 Copyright 2004, Oracle. All rights reserved.
Using Java with Oracle 10g
Oracle
database
Web
serverClient
Application
server
PresentationBusiness
logic
Data
OracleApplicat ion Server
Java and Oracle 10g
Oracle 10g is a complete and integrated platform, which supports all the server-side
requirements for Java applications. Oracle 10g comprises the following:
Oracle Database 10g
In 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 10g
The 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.
Instructor Note
For more architectural information about Oracle Application Server 10g, direct students to thevarious eClasses that are available on the Oracle Learning Network.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
42/329
Oracle10 : Java Pro rammin 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 Kit
Sun 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:
cl asses. zi p located in the jdk_home\ l i b for JDK 1.1.x or earlier r t . j ar located in the jdk_home\ j r e\ l i b for Java SDK 1.2.x or later
Other Java J2SE Tools j db is the Java class debugger. It is similar to the dbx or gdb debuggers on UNIX. j ar is used to create Java Archive (JAR) files, which are zipped Java programs. j avah is used to generate C files for native methods. j avakey supports the generation of certification keys for trusted Java code.
j avap is used to disassemble Java bytecodes into human-readable format. nat i ve2asci i converts Java source code to Latin 1 characters. ser i al ver is used to generate version numbers for classes.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
43/329
Oracle10 : Java Pro rammin 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 Need
Java 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 to
supercomputer 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.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
44/329
Oracle10 : Java Pro rammin 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 Environment
The 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
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
45/329
Oracle10 : Java Pro rammin 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 Environment
JDeveloper 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 orclasses in a project. The files may be Java source files, . cl ass 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.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
46/329
Oracle10 : Java Pro rammin 1-24
1-24 Copyright 2004, Oracle. All rights reserved.
Oracle10g Products
Oracle 10g Products
Oracle Database 10g
The 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 10g
The 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 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.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
47/329
Oracle10 : Java Pro rammin 1-25
1-25 Copyright 2004, Oracle. All rights reserved.
Summary
In th is lesson, you should have learned the following: Java code is compiled into platform-independent
bytecodes.
Bytecodes are interpreted by JVM.
Java appl ications can be stand-alone or
implemented across an Internet-computing model.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
48/329
Copyright 2004, Oracle. All rights reserved.
Defining Object-Oriented Principles
Schedule: Timing Topic
60 minutes Lecture
20 minutes Practice
80 minutes Total
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
49/329
Oracle10 : Java Pro rammin 2-2
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: c lasses,
objects, and methods Describe the value of Reusable Software
Components
Examine the OO model that is used in this course
Lesson Aim
This 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.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
50/329
Oracle10 : Java Pro rammin 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 programmingenvironment.
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.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
51/329
Oracle10 : Java Pro rammin 2-4
2-4 Copyright 2004, Oracle. All rights reserved.
What Is Modeling?
Models perform the following funct ions: Descr ibe 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 Metaphor
Imagine 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. Thecontractor 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.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
52/329
Oracle10 : Java Pro rammin 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. Acustomer 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.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
53/329
Oracle10 : Java Pro rammin 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.
Att ribute: Ink amount
At tr ibute: Cash available
Object: My blue pen
Object: Acme Bank ATM
An Object s Attr ibutes Maintain Its State
All 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 thecurrent 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 attributevalues 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.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
54/329
Oracle10 : Java Pro rammin 2-7
An Object s Attr ibutes Maintain Its State (cont inued)
Typical Attributes
As with operations, different objects store different attributes. For example, the Acme BankATMobject has attributes such as cash available, cards recognized, ATM code, and so on. Thebl ue 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.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
55/329
Oracle10 : Java Pro rammin 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 Behavior
The 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 ATMobject has operations such as withdraw, print receipt, swipe card, and so on. Alternatively, the
my bl ue 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.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
56/329
Oracle10 : Java Pro rammin 2-9
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 not want to model:
At tr ibutes: Ink color
Operations: Refill , change color, point, write
Context: Product catalog
Real-world attributes/operations that you may want to model:
At tributes: Model, manufacturer, pr ice
Operations: Change price
Objects Are Modeled as Abstractions
How do you decide what operations and attributes are relevant to the model of themy bl uepen 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 theway 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?
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
57/329
Oracle10 : Java Pro rammin 2-10
Objects Are Modeled as Abstractions (continued)
Every Object Is Unique
By definition, each object instance has a unique identity; even if two or more objects haveidentical states, that is, if their attribute values are the same, the system always treats them asdifferent objects. When you create objects in software, you are given ahandle to the object,called an object reference in the Java language. In Java, this handle or object reference is given aname by which it can refer to the object.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
58/329
Oracle10 : Java Pro rammin 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 Composition
For 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.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
59/329
Oracle10 : Java Pro rammin 2-12
Defining Object Composition (continued)
Aggregation
This 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 acomposition.
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.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
60/329
Oracle10 : Java Pro rammin 2-13
2-13 Copyright 2004, Oracle. All rights reserved.
The Donut Diagram
getAge()
Client or
sender
Person
Messagename
address
birthdate
getName
setBirthdate getAge
getAddress setAddress
The Donut Diagram
The 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 Per son object by sending messages to it; that is, by invokingits public methods. The client does not know how theget Age 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 namedObject-
Oriented Analysis and Design using the Unified Modeling Language (UML).
For further information, refer to http://education.oracle.com.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
61/329
Oracle10 : Java Pro rammin 2-14
2-14 Copyright 2004, Oracle. All rights reserved.
Guided Practice:
Spot the Operations and Attributes
Spot the Operations and Attributes
For 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
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
62/329
Oracle10 : Java Pro rammin 2-15
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 Col lect ion of Col laborat ing Objects
An 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 ofthe functionality that is required to support the task.
The association between objects is achieved dynamically through areference. (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 areference to the other object. In Java, one way to create an object is to use thenewoperator.
Movi e m1 = new Movi e( )
In this example, the class definition is called Movi e that is used as a data type for the variablem1. 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.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
63/329
Oracle10 : Java Pro rammin 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 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 a
particular object:myPen.write( ): Object-oriented programming
write (myPen): Traditional structuredprogramming
Objects Interact Through Messages
Methods 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 specific
piece of code (some subroutine). For example, using the Pen example in the slide:Pen myPen = new Pen( ) ; / / get r ef erence t o a pen obj ectmyPen. wr i t e( ) ; / / Send wr i t e( ) message t o myPen
When you send a message, the specific piece of code that gets executeddepends on the class (thetype) of the receiver object. This is required to enable the principle ofpolymorphism, to exist.
Remember, you send a message to an object. This notion of a targeted recipient is different from
calling a procedure.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
64/329
Oracle10 : Java Pro rammin 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 Type
In 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 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 and
behavior 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.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
65/329
Oracle10 : Java Pro rammin 2-18
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 classes and objects interchangeably.
Classes define objects.
My blue pen ops: write, refill
attr ibs: 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 youinterested 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 yourcurrent viewpoint.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
66/329
Oracle10 : Java Pro rammin 2-19
2-19 Copyright 2004, Oracle. All rights reserved.
Comparing Classes and Objects
Classes are static definit ions that you can use tounderstand 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 dif ferentiate between
the two meanings.
Comparing Classes and Objects
Objects 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.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
67/329
Oracle10 : Java Pro rammin 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
St r i ng; a typical program contains many St r i ng 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.
-
7/25/2019 Oracle10g Java Programming Instructor Guide - Volume 1.pdf
68/329
Oracle10 : Java Pro rammin 2-21
2-21 Copyright 2004, Oracle. All rights reserved.
What Is Encapsulation?
Encapsulation hides the internal structure andoperations 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 Encapsulation
With 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 touse 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 b