SL210_OH

188
Sun Educational Services Migrating to OO Programming With Java Technology December 2000 Migrating to OO Programming With Java Technology SL-210

description

SL210_OH

Transcript of SL210_OH

Page 1: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology December 2000

Migrating to OO ProgrammingWith Java Technology

SL-210

Page 2: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology December 2000

Preface

About This Course

Page 3: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Preface, slide 2 of 17Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Course Goal

This course provides the necessary concepts for developerswith a non-object-oriented background to begin the move toJava™ technology.

This is not a Java technology programming course; it is apreparatory course that provides the necessary knowledge fortaking SL-275: Java Programming Language.

Page 4: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Preface, slide 3 of 17Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Course Overview

• Object-oriented analysis and design

• Basic syntax for Java technology classes ("Java classes")and structure of Java technology programs ("Javaprograms")

• Unified Modeling Language (UML) notation

Page 5: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Preface, slide 4 of 17Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Course Expectations

• This is not a programming course; no computers will beused.

• OO is a new paradigm and cannot be related to priornon-OO programming experience.

Page 6: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Preface, slide 5 of 17Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, December 2000, Revision A.3

Course Map

Page 7: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Preface, slide 6 of 17Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Module-by-Module Overview

• Module 1 – "Objects"

• Module 2 – "Classes"

• Module 3 – "Using Java Classes"

• Module 4 – "Using Java Methods"

• Module 5 – "Object Interaction"

• Module 6 – "Object-Oriented Analysis and DesignUsing UML"

Page 8: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Preface, slide 7 of 17Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Course Objectives

• Identify objects in a problem domain

• Group objects in classes

• Identify objects’ relationships to one another

• Use inheritance to create a specialized Java class

• Describe polymorphism

• Use encapsulation when creating Java classes

Page 9: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Preface, slide 8 of 17Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Course Objectives

• Define methods for a class

• Describe basic Java technology programming structureguidelines

• Implement the understanding gained through OO andJava technology syntax by developing UML diagramsto analyze a problem domain

Page 10: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Preface, slide 9 of 17Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Skills Gained by Module

Meaning of:

• Black boxes

• Gray boxes

Module

Skills Gained 1 2 3 4

Skill or Objective 1

Skill or Objective 2

Skill or Objective 3

Skill or Objective 4

Page 11: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Preface, slide 10 of 17Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Guidelines for Module Pacing

Module Day 1 Day 2 Day 3

About This Course A.M.

Objects A.M.

Classes A.M./P.M.

Using Java Classes P.M.

Using Java Methods A.M.

Object Interaction A.M./P.M.

Object-Oriented Analysis and DesignUsing UML

A.M./P.M.

Page 12: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Preface, slide 11 of 17Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Topics Not Covered

• Advanced Java technology programming – Covered inSL-275: Java Programming Language

• Advanced OO concepts – Covered in OO-226: Object-Oriented Application Analysis and Design for JavaTechnology (UML)

Page 13: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Preface, slide 12 of 17Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

How Prepared Are You?

• Six months or more of experience programming

• Experience designing applications

Page 14: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Preface, slide 13 of 17Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Introductions

• Name

• Company affiliation

• Title, function, and job responsibility

• Programming experience

• Reasons for enrolling in this course

• Expectations for this course

Page 15: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Preface, slide 14 of 17Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

How to Use Course Materials

• Relevance

• Overhead image

• Lecture

• Exercise

• Check Your Progress

• Think Beyond

• Acronym glossary

Page 16: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Preface, slide 15 of 17Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Icons

• Demonstration

• Reference

• Discussion

• Exercise

Page 17: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Preface, slide 16 of 17Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Typographical Conventions

Typeface orSymbol

Meaning Example

AaBbCc123 The names of commands, files,and directories;on-screen computer output

Edit your .login file.Use ls -a to list all files.system% You have mail.

AaBbCc123 What you type, contrasted withon-screen computer output

system% suPassword:

AaBbCc123 Command-line placeholder—replace with a real value

To delete a file, type rmfilename .

AaBbCc123 Book titles, new words orterms, or words to beemphasized

Read Chapter 6 in User’sGuide. These are called classoptions.You must be root to do this.

Page 18: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Preface, slide 17 of 17Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Syntax Conventions

• Syntax and example

type variable_identifier

int myFirstVariable;

• Optional elements in square brackets

[ class_modifier ] class name { block }

• Variables in italics

Page 19: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology December 2000

Module 1

Objects

Page 20: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 1, slide 2 of 26Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Objectives

• Describe abstraction and how it is used in objectorientation

• Identify objects and non-objects from a problem domain

• Describe object encapsulation

Page 21: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 1, slide 3 of 26Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Overview of Object Orientation

• Technique for system modeling

• Models the system as a number of related objects thatinteract

• Similar to the way people view their environment

Page 22: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 1, slide 4 of 26Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Abstraction

• Is the process of ignoring details to concentrate onessential characteristics

• Is the primary means of coping with complexity

• Simplifies users’ interaction with abstracted objects

• Has two types: functional abstraction and dataabstraction

Page 23: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 1, slide 5 of 26Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Functional Abstraction

• Unabstracted function

for (; *s== ' ' || *s == '\t'; s++);sign=1;if (*s =='+' || *s == '-')

sign = (*s++ == '+') ? 1: -1;for (n=0; *s > '0' && *s <= '0'; s++)

n = 10 * n + *s - '0';value = sign * n;

Page 24: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 1, slide 6 of 26Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Data Abstraction

• Deals with data types

• Allows details of the internal representation of a datatype to be ignored

• Involves functional abstraction

Page 25: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 1, slide 7 of 26Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Identifying Objects

• Object can be a sentence, bank account, number, or car

• Objects are

• Things

• Real or imaginary

• Simple or complex

Page 26: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 1, slide 8 of 26Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Identifying Objects

• Example objects

Painter’s paletteSatellite dish Employee

X + Yi

Complex number Bank account Bicycle

Page 27: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 1, slide 9 of 26Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Case Study

DirectClothing, Inc. nouns• catalog

• clothing

• subscribers

• closeout items

• monthly sale items

• normal items

• order

• customer

• CSR (customer servicerepresentative)

• order entry clerk

• supplier

• payment

• warehouse

• credit card

• order entry

• mail order

• fax order

• online order

• inventory

• back-ordereditems

• system

• Internet

• business

• year

• month

• order form

• check

Page 28: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 1, slide 10 of 26Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Identifying Object Attributes andOperations

• Example:

• Cloud attributes – size, water content, shape

• Cloud operations – rain, thunder, snow

• Attributes: an object’s characteristics

• Operations: what an object can do

Page 29: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 1, slide 11 of 26Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Case Study

• For the Order object, the following attributes andoperations could be defined:

• Attributes: orderNumber, customerNumber,dateOrdered, amountOwed

• Operations: whatCustomer, calcAmountOwed,printOrder, payOrder

• Discussion – What would be the attributes andoperations for the Customer object?

Page 30: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 1, slide 12 of 26Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Testing an Identified Object

• Use the following criteria to test object validity:

• Relevance to the problem domain

• Need to exist independently

• Having attributes and operations

Page 31: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 1, slide 13 of 26Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Relevance to the Problem Domain

• Does it exist within the boundaries of the problemstatement?

• Is it required in order for the system to fulfill itsresponsibility?

• Is it required as part of an interaction between a userand the system?

• Can objects sometimes be a characteristic of otherobjects?

Page 32: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 1, slide 14 of 26Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Case Study

• The Order object passes the relevance test:

• Exists within the boundaries of the problemstatement

• Is required for the system to fulfill its responsibilities

• Is required as part of an interaction between a userand the system

• Discussion – Test the other candidate objects in the casestudy.

Page 33: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 1, slide 15 of 26Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Independent Existence

• To be an object and not a characteristic of another object,the object must need to exist independently.

Page 34: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 1, slide 16 of 26Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Case Study

• Can an Order object exist without any of the otherobjects? It can, but it must have an associated Customerobject.

• Address could be an attribute of Customer, but in thiscase study it is advantageous for Address to be aseparate object.

• Discussion – Are there any other objects in the casestudy that need to exist independently?

Page 35: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 1, slide 17 of 26Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Attributes and Operations

• An object must have attributes and operations.

• If it does not, it is probably an attribute or operation ofanother object.

Page 36: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 1, slide 18 of 26Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Case Study

• The Order object has many attributes and operationsdefined as do most of the candidate objects.

• Are there any objects listed on page 1-10 that do nothave attributes and operations?

Page 37: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 1, slide 19 of 26Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Encapsulation

• Encapsulation separates the external aspects of an objectfrom the internal implementation details.

• Internal changes need not affect external interface.

Page 38: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 1, slide 20 of 26Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Parts of an Encapsulated Object

• Each physical object has

• Public interface (external)

• Implementation (internal)

• Internal information (information for implementation)

Page 39: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 1, slide 21 of 26Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Implementing Encapsulation

• An object’s attributes and operations are its members.

• The members of an object can be public or private.

• In pure OO systems, all attributes are private and can bechanged or accessed only through public operations.

Page 40: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 1, slide 22 of 26Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Case Study

• Using the Order object from the case study, you wouldmake all attributes private and need to create publicoperations to get and set values for each of theattributes.

• All other operations, such as calcAmountOwed andpayOrder, would also be public.

• However, you could decide that the calcAmountOwedshould be private so other objects cannot have access tocalculate the amount owed.

• Discussion – How would you encapsulate the Customerobject?

Page 41: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 1, slide 23 of 26Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Module Summary

• Object

• Attributes

• Operations

• Abstraction

• Data hiding

• Encapsulate

• Member

Page 42: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 1, slide 24 of 26Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Exercise: Identifying Objects

• Exercise objective

• Preparation

• Tasks

• Exercise summary

Page 43: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 1, slide 25 of 26Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Check Your Progress

• Describe abstraction and how it is used in objectorientation

• Identify objects and non-objects from a problem domain

• Describe object encapsulation

Page 44: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 1, slide 26 of 26Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Think Beyond

• What if you have several objects in a system that sharemany characteristics but are different, such as differenttypes of musical instruments?

• How would you write them or categorize them topromote reuse?

Page 45: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology December 2000

Module 2

Classes

Page 46: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 2, slide 2 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Objectives

• Group objects with similar attributes and commonoperations in classes

• Explain how classes are used to define objects

• Define inheritance and explain how it relates tosoftware reuse

• Define generalization and specialization and how theyrelate to inheritance

• Define polymorphism and explain how inheritancepromotes polymorphism

• Define abstract classes

Page 47: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 2, slide 3 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Class Overview

• Object is an instance: a specific leaf, ball, car, or coin

• "A car" is a class; "my car" is an object

Objects ofa Leaf class

Objects of aBall class

Page 48: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 2, slide 4 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Case Study

For each object identified in the order entry system, define acorresponding class.

Page 49: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 2, slide 5 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Generalization

• Example: Transport is a generalization of several classesthat provide transportation.

• Generalization identifies and defines the commonattributes and operations in a collection of objects.

Page 50: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 2, slide 6 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Case Study

• The order entry clerk and customer servicerepresentative objects are considered identical and anEmployee class will be created. You can create aCustomerServiceRepresentative or an OrderEntryClerkobject from the Employee class.

• The Customer object and the Employee class also havesimilarities. You could create a Person class that wouldcontain those similar attributes; you could also create anAddress class.

• Discussion – What other generalizations can you find inthe objects?

Page 51: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 2, slide 7 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Inheritance

Example: Soccer Ball class can inherit members from a Ballclass.

Ball

Soccer Ball BaseballSubclasses

Superclass

Basketball

Page 52: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 2, slide 8 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Inheritance

• Is a mechanism for defining a new class in terms of anexisting class

• Allows you to group related classes so that they can bemanaged collectively

• Promotes reuse

• Allows you to hide or override inherited members

• Relevant terms: generalization, specialization, override

Page 53: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 2, slide 9 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, December 2000, Revision A.3

Case Study

Both the Customer and Employee classesextend Person.

Discussion – What other classes could youuse in this system to promote reuse?

attributes

firstNamelastNameinitial

getNamemethods

Customer

CS Rep.

Employee

OE Clerk

Person

ID

attributes

firstNamelastNameinitial

getNamegetSalutation

methods

ID

*salutation

attributes

firstNamelastNameinitial

getNamegetSSN

methods

grantRaise

ID

*SSN

Page 54: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 2, slide 10 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Specialization

Specialization is inheritance with the addition andmodification of methods to solve a specific problem.

Transport

Bicycle PlaneClasses:

Generalized

Automobile

class:

Car Truck Mountain Road Private

CommercialSpecializedclasses:

Page 55: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 2, slide 11 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Polymorphism

• Allows you to implement an inherited operation in asubclass

• Works only when the common operation gives the samesemantic result

• Implementation of a polymorphic function depends onthe object it is applied to

• Can be used only with inheritance

Page 56: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 2, slide 12 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Another Example

• Consider a general class called WritingInstrument

• The class has an operation called write

• What are examples of objects in the classroom thatcould be subclasses of WritingInstrument?

• How is the write operation polymorphic?

Page 57: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 2, slide 13 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Case Study

• In the order-entry system, you could use polymorphismwith the Person object’s giveName operation. Use it asis for the Employee object, but all Customers wouldgive the salutation that should be used with their name,in addition.

• Discussion – What other operations could bepolymorphic?

Page 58: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 2, slide 14 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Key Points of Polymorphism

• Based on inheritance

• Can be applied to any operation that is inherited from asuperclass

• Subclasses that override an inherited operation areproviding another form of the operation, hence the termpolymorphism

Page 59: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 2, slide 15 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Abstract Classes

• A class with at least one abstract operation is an abstractclass.

• A subclass of an abstract class needs to provide animplementation of all abstract operations or it is also anabstract class.

• An abstract class cannot be instantiated (you cannotcreate objects of an abstract class).

• Operations in an abstract class are placeholders.

Page 60: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 2, slide 16 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Another Example

• Consider implementing classes for a circle, rectangle,and triangle.

• Operations for these classes must include setColor andsetBorderStyle.

• You decide to create an abstract class called share withtwo abstract operations: setColor and setBorderStyle

• The subclasses must override these abstract operationsand provide implementation code that makes sense forthe subclass shape.

Page 61: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 2, slide 17 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Case Study

• The Person object in the order-entry system is anabstract class; you would instantiate a customer or anemployee, but not a person.

• Discussion – What other abstract classes could youuse in an order-entry system?

Page 62: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 2, slide 18 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Key Points of Abstract Classes

• A class with at least one abstract operation (an operationfor which there is no implementation code defined) isan abstract class.

• Subclasses of an abstract class should provide animplementation of all inherited abstract operations. Ifnot, the subclasses are abstract classes.

• Abstract classes are referred to as templates for classes.No instance of an abstract class can be created.

Page 63: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 2, slide 19 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Module Summary

• Class

• Object

• Generalization

• Inheritance

• Overriding

• Specialization

• Polymorphism

• Abstract class

Page 64: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 2, slide 20 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Exercise: Grouping Objects in Classes

• Exercise objective

• Preparation

• Tasks

• Exercise summary

Page 65: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 2, slide 21 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Check Your Progress

• Group objects with similar attributes and commonoperations in classes

• Explain how classes are used to define objects

• Define inheritance and explain how it relates tosoftware reuse

• Define generalization and specialization and how theyrelate to inheritance

• Define polymorphism and explain how inheritancepromotes polymorphism

• Define abstract classes

Page 66: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 2, slide 22 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Think Beyond

• What components would need to be specified in a Javaprogramming language statement to describe a class?

Page 67: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology December 2000

Module 3

Using Java Classes

Page 68: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 2 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Objectives

• Code class declarations

• Define the primitive types

• Declare class variables using primitive types

• Declare class variables using reference types

• Name Java classes and other identifiers according toJava programming language guidelines

• Use inheritance correctly

• Use abstract classes

Page 69: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 3 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Objectives

• Use the import statement to include classes in aprogram

• Use the package statement to group classes in a classhierarchy

• Understand the structure of a Java program

Page 70: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 4 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Declaring Classes

[ class_modifier ] class class_identifier{ block }

• class_modifier – optional; public , abstract , orfinal

• class – keyword indicating class declaration

• class_identifier – name of the class

• block – for variables and methods that make up the class

Page 71: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 5 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Case Study

• Code an Order class for the order-entry program likethis:

public class Order { }

• Discussion – How would you code the class declarationfor the other classes?

Page 72: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 6 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Variables

• Variable is the Java programming language term forattributes.

• Each must have type and unique identifier.

Page 73: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 7 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Identifiers

• Identifiers are names assigned to classes, variables, andmethods.

• The first character must be one of the following:

• An uppercase letter (A–Z)

• A lowercase letter (a–z)

• The underscore character (_)

• The dollar character ($)

Page 74: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 8 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Identifiers

• The second and subsequent characters of an identifiermust be any of the following:

• Any character from previous list

• Numeric characters (0–9)

• In multiple-word identifiers, start each subsequentword with a capital letter.

• Java keywords may not be used.

• The Java programming language is case sensitive.

Page 75: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 9 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Java Primitive Types and ReferenceTypes

• All variables have a type from a Java technologyprimitive type or reference type.

• Type restricts values that can be assigned to a variable.

• Variable declaration syntax is

type variable_identifier

Page 76: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 10 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Java Primitive Types and ReferenceTypes

• Primitive types

• byte

• short

• int

• long

• float

• double

• char

• boolean

Page 77: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 11 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Integral Types

• Is used to store whole numbers

• Counts zero as positive

Name or Type Integer Length Range

byte 8 bits -27 ... 27 -1

short 16 bits -215 ... 215 -1

int 32 bits -231 ... 231 -1

long 64 bits -263 ... 263 -1

Page 78: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 12 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Floating Point Types

• Floating point types store numbers with values to theright of the decimal point.

• Largest or smallest value cannot be known becausefloating point types allow variable accuracy.

• Two pre-defined constants denote the extents of thetypes, POSITIVE_INFINITY and NEGATIVE_INFINITY .

Name or Type Float Lengthfloat 32 bits

double 64 bits

Page 79: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 13 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Textual Type: char

• Stores a single character

• Uses single quotation marks around value:

myFirstCharacter = ’g’;

• Can store any value from the Java technology characterset (Unicode)

Page 80: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 14 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Logical Type: boolean

• Stores one of two values: true or false

• Is used in decision-making

Page 81: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 15 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Object References

• Hold a handle of an object

• Can only refer to objects of the declared type or of asubclass type

Page 82: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 16 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Object References

• Declaring an object reference:

type variable_identifier

Computer laptop;

• Creating objects:

variable_identifier = new class_name

laptop = new Computer();

• Using object references

int first = 9;

int second = first;

Computer laptop = new Computer();

Computer anotherReferenceToLaptop = laptop;

Page 83: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 17 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Strings

• Reference type used to store a sequence of characters

• Creating String s:

• Method 1

String variable_identifier = new String" string_value ");

String animal = new String("dog");

• Method 2

String variable = " string_value ";

String animal = "dog";

Page 84: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 18 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Case Study

• The Person class declaration with the variables definedwould appears as shown:

1 class Person2 {3 String firstName;4 String lastName;5 String initial;6 String ID;7 Address homeAddress8 }

• How would you code the class declaration andvariables for the Order class?

Page 85: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 19 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Encapsulation

• Encapsulation hides implementation from users

• All variables are should be private (hidden inimplementation)

• Private variables can be accessed only through publicmethods (operations)

Page 86: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 20 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Case Study

The following class demonstrates making all variables privateand making the operations public:

1 class Person2 {3 private String firstName;4 private String lastName;5 private String initial;6 private int ID;7 private Address homeAddress;89 public String getName(){return firstName;}10 public void setFirstName(String fName){}11 public void setLastName(String lName){}12 public void setInitial(String init){}13 public int getID(){return ID;}14 public void setID(Sting id){}15 public Address getAddress(){return homeAddress;}16 public void setAddress(Address addr){}17 }

Page 87: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 21 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Inheritance

• Example: Manager and Engineer classes both havecharacteristics of an Employee .

• Common items are defined in one class and subsequentclasses base themselves on that class.

Page 88: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 22 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, December 2000, Revision A.3

Using Inheritance

• Declaration of Manager and Engineerclasses:

1 class Manager2 {3 int employeeNumber;4 String name;5 int departmentNumber;6 int extensionNumber;7 int salary;8 int numberOfWorkers;9 // and so on10 }

1 class Engineer2 {3 int employeeNumber;4 String name;5 int departmentNumber;6 int extensionNumber;7 int salary;8 Manager worksFor;9 // and so on10 }

Page 89: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 23 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, December 2000, Revision A.3

Using Inheritance

• Syntax for inheritance:

class subclass_name extends superclass_name{ block }

• Example:

1 class Employee2 {3 int employeeNumber;4 String name;5 int departmentNumber;6 int extensionNumber;7 int salary;8 // and so on9 }

1 class Manager extends Employee2 {3 int numberOfWorkers;4 // and so on5 }67 class Engineer extends Employee8 {9 Manager worksFor;10 // and so on11 }

Page 90: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 24 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Testing Inheritance

• In the Java programming language, a class can inheritfrom only one superclass at a time.

• It is very important to use inheritance only if it is validor unavoidable.

• Check validity using the “is a” phrase (“a Manager is anEmployee”).

Page 91: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 25 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, December 2000, Revision A.3

Testing Inheritance

• Class declaration with duplication:

1 class Cycle2 {3 int numberOfWheels;4 int numberOfSeats;5 float luggageCapacity;6 // and so on7 }8 class Boeing7479 {10 int numberOfWheels;11 int numberOfSeats;12 float luggageCapacity;13 int numberOfWings;14 // and so on15 }

• First attempt to use inheritance:

1 class Cycle2 {3 int numberOfWheels;4 int numberOfSeats;5 float luggageCapacity;6 // and so on7 }8 class Boeing747 extends Cycle9 {10 int numberOfWings;11 // and so on12 }

Page 92: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 26 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, December 2000, Revision A.3

Testing Inheritance

• Correct use of inheritance:

1 class Vehicle2 {3 int numberOFWheels;4 int numberOfSeats;5 float luggageCapacity;6 // and so on7 }89 class Cycle extends Vehicle10 {11 // and so on12 }1314 class Boeing747 extends Vehicle15 {16 int numberOfWings;17 // and so on18 }

Page 93: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 27 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Case Study

• Remember the example of the Customer and Employeeclasses; you could code the following class declarationsfor inheritance:

class Customer extends Person {}

class Employee extends Person {}

• Discussion – What other classes would use inheritance?

Page 94: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 28 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Containment Classes

• Example: Kitchen class can be used to contain Stoveand Refrigerator classes

1 class Stove2 {3 //whatever the class does4 }56 class Refrigerator7 {8 // whatever the class does9 }1011class Kitchen12{13 Stove myStove;14 Refrigerator myRefrigerator;15 // and so on16}

• Used to contain, or collect, references to related objectsin order to manipulate them

Page 95: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 29 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Testing Containment

• Use the "has a" phrase to test containment validity (aKitchen has a Stove; a Kitchen has a Refrigerator)

Page 96: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 30 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, December 2000, Revision A.3

Case Study

• The Person class is a containmentclass because it contains the homeaddress of the person.

1 class Person2 {3 private String firstName;4 private String lastName;5 private String initial;6 private int ID;7 private Address homeAddress;89 public String getName(){return firstName;}10 public void setFirstName(String fName){}11 public void setLastName(String lName){}12 public void setInitial(String init){}13 public int getID(){return ID;}14 public void setID(Sting id){}15 public Address getAddress(){return homeAddress;}16 public void setAddress(Address addr){}17 }

• Which other classes could becontainment classes?

Page 97: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 31 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Abstract Classes and Inheritance

• Example: A Drawing class contains methods for avariety of drawing features, implemented in a platform-independent way.

• Abstract classes can define the methods that shouldexist; the methods will be implemented in subclasses.

• Abstract classes and operations are marked asabstract .

• You cannot create an instance of an abstract class.

• Subclasses must provide implementations for allabstract methods in their superclasses.

Page 98: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 32 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Using Abstract Classes

1 public abstract class Drawing2 {34 public abstract void drawDot(int x, int y);5 public void drawLine(int x1, int y1,6 int x2, int y2)7 {8 // draw using the drawDot() method repeatedly.9 }10 }

Page 99: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 33 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Case Study

• Code an abstract class Person :

1 public abstract class Person2 {3 private String firstName;4 private String lastName;5 private String initial;6 private int ID;7 private Address homeAddress;89 public String getName(){return firstName;}10 public void setFirstName(String fName){}11 public void setLastName(String lName){}12 public void setInitial(String init){}13 public int getID(){return ID;}14 public void setID(Sting id){}15 public Address getAddress(){return homeAddress;}16 public void setAddress(Address addr){}17 }

• How would you implement other abstract classes?

Page 100: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 34 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Classes and Packages

• A package is a grouping of related classes.

• You can

• Import classes from a package

• Package classes in your programs

Page 101: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 35 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Java 2 Platform Class Library Packages

• Java 2 platform comes with a standard set of classes thatimplement most basic operations.

• java.lang contains core classes.

• java.awt deals with the graphical user interface.

• java.applet provides applet-specific behavior.

• java.net performs network related operations.

• java.io contains classes that deal with file I/O.

• java.util contains utility classes.

Page 102: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 36 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Grouping Classes in Packages

• Packages can be used when distributing an application.

• Indicate that classes in a source file belong to aparticular package by using the package statement:

package package_name

1 // Class Employee of the Finance department for the2 // ABC company3 package abc.financedept;45 public class Employee6 {7 ...8 }

• All classes in the source file are within the namedpackage.

Page 103: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 37 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Case Study

Discussion – What parts of the order-entry system would youpackage? Code the package declaration.

Page 104: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 38 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Using Classes Stored in Packages

• To use packages, use the import statement at the top ofyour program:

import package_name

• Example: Use the import statement and just the classname Employee to access the Employee class in theabc.financeDept package:

1 // Class Manager belongs to the default package.2 import abc.financeDept.*;3 public class Manager extends Employee4 {5 String department;6 Employee [] subordinates;7 }

Page 105: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 39 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Coding Structure

• Java is a free-format programming language with fewrules:

• Source file can contain three elements, in this order:package declaration (optional), import statements,and class and interface definitions.

• Source file name must match the public class name inthe source file.

• You can have only one public class in a source file.

• The Java source file is always namedpublic_class_name .java ; the compiled version isone or more files named class_name .class .

Page 106: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 40 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Case Study

The following code example shows how to add the classCustomer to the package OrderEntry and import the Personand Address classes from the OrderSupport package:

1 package OrderEntry;2 import OrderSupport.Person;3 import OrderSupport.Address;45 public class Customer extends Person6 {7 private Address shipTo;89 public Address getShipTo(){}10 public void setShipTo(Address addr){}11 }

Page 107: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 41 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Module Summary

1. Defines a block that contains all your attributes andoperations.

2. Access modifier that gives the entire world access.

3. Modifier that restricts the use of subclassing.

4. Primitive data type that may have the values true orfalse.

5. Primitive data type that holds textual information.

6. Primitive data type that whole numbers default to.

7. Primitive data type that is most often used fordecimal numbers.

Page 108: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 42 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

8. Keyword that allocates space and initializes membervariables.

9. Class from java.lang that holds textual information.

10.Keyword that allows you to do subclassing.

11.Keyword that defines a class that cannot be created.

12.Keyword that defines this code as part of a library.

13.Keyword that loads code from a library.

Page 109: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 43 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Exercise: Implementing the ClassDiagram

• Exercise objective

• Preparation

• Tasks

• Exercise summary

Page 110: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 44 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Check Your Progress

• Code class declarations

• Define the primitive types

• Declare class variables using primitive types

• Declare class variables using reference types

• Name Java classes and other identifiers according toJava programming language guidelines

• Use inheritance correctly

• Use abstract classes

Page 111: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 45 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Check Your Progress

• Use the import statement to include classes in aprogram

• Use the package statement to group classes in a classhierarchy

• Understand the structure of a Java program

Page 112: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 3, slide 46 of 46Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Think Beyond

Now that you have written a class in the Java programminglanguage, how do you write an operation (method)? Whatinformation would you need to provide?

Page 113: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology December 2000

Module 4

Using Java Methods

Page 114: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 4, slide 2 of 31Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Objectives

• Define class behavior using methods

• Declare a public method for encapsulation

• Pass arguments to a method

• Describe a method’s signature

• Explain how method overloading works

• Use a constructor to instantiate an object

Page 115: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 4, slide 3 of 31Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Method Overview

• Method is the Java technology term for an OO operation.

• Methods separate the statements into code blocks thatcan run independently of each other.

• Methods can invoke each other.

• All programs use methods.

Page 116: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 4, slide 4 of 31Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Why Are Methods Necessary?

• Methods make programs more readable and easier tomaintain.

• Methods make development and maintenance quicker.

• Methods are central to reusable software.

• Methods avoid duplication.

• Methods are required for encapsulation.

Page 117: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 4, slide 5 of 31Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Declaring Methods

• Methods are written inside the body of a class.

modifiers return_type method_identifier([arguments]) {method_body}

• modifiers – Keywords that modify the waymethods are stored or how they run

• return_type – Result of calculation or query

• method_identifier – Identifier (name)

• arguments – (Optional) Data for the method

• method_body – Sequence of statements to performthe task

Page 118: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 4, slide 6 of 31Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, December 2000, Revision A.3

Case Study

• The Person class attributes andmethod declarations:

1 public abstract class Person2 {3 private String firstName;4 private String lastName;5 private String initial;6 private int ID;7 private Address homeAddress;89 public String getName(){return firstName;}10 public void setFirstName(String fName){}11 public void setLastName(String lName){}12 public void setInitial(String init){}13 public int getID(){return ID;}14 public void setID(String id){}15 public Address getAddress(){return homeAddress;}16 public void setAddress(Address addr){}17 }

• Discussion – How would you code themethod declarations for the otherobjects?

Page 119: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 4, slide 7 of 31Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Invoking Methods

object_reference . method_identifier ([ arguments ])

1 class VoidMethodInvocation2 {3 public static void main (String args[])4 {5 ClassOne one = new ClassOne();6 one.returnNothing();7 }8 }910class ClassOne11{12 public void returnNothing()13 {14 //whatever the method does15 }16}

Page 120: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 4, slide 8 of 31Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, December 2000, Revision A.3

Case Study

• Customer.java source file:

1 package OrderEntry;2 import OrderSupport.Address;3 public class Customer extends Person4 {5 public static void main (String args[])6 {7 Adress shipTo = new Address();8 shipTo.printLabel();9 }10 }

• Address.java source file:

1 package OrderSupport;23 public class Address4 {5 private String addressLine1;6 private String addressLine2;7 private String city;8 private String state;9 private String postalCode;10 private String country;1112 public void printLabel()13 {14 System.out.println(addressLine1);15 if (addressLine2 != null)16 System.out.println(addressLine2);17 System.out.println(city + ", "+ state +18 postalCode + country);19 }20 }

Page 121: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 4, slide 9 of 31Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Object Methods

• Method must be preceded by the reference to the objectand the dot operator (“.”).

1 class MethodInvocation2 {3 public static void main (String args[])4 {5 ClassOne one = new ClassOne();6 int i = one.returnAnInt();7 int j = i * one.returnAnInt() + 6;8 System.out.println("An int: " +

one.returnAnInt());9 }10 }1112 class ClassOne13 {14 public int returnAnInt()15 {16 return 9;17 }18 }

Page 122: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 4, slide 10 of 31Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

static Methods

• The static modifier should be used with genericutilities or methods that may need to be called any timewithout first instantiating an object from the class.

1 class StaticExample2 {3 public static void main (string args[])4 {5 double rand = Math.random();6 System.out.println("A random number: " + rand);7 }8 }

Page 123: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 4, slide 11 of 31Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Case Study

Discussion – What static methods could you use in the order-entry example?

Page 124: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 4, slide 12 of 31Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

The this Reference

• Means "reference to the same object"

• Takes the place of an explicit object reference

• Example: Line 5 refers to a method2 method for thecurrent class

1 class Example2 {3 void method1()4 {5 this. method2();6 }7 void method2()8 {9 //whatever method2 does10 }11}

Page 125: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 4, slide 13 of 31Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Passing Arguments

• You must give values for any methods with argumentswhen invoking the method.

• Arguments must be declared as a type-variable pair:

method_name ( type variable_identifier )

myMethod (int myInt)

Page 126: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 4, slide 14 of 31Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Passing Arguments

1 class StoreVal2 {3 int value;4 // method declaration for a method with no5 // return value and one int argument6 void setValue(int val)7 {8 // the this keyword sets value to val9 this.value = val;10 }11 //method declaration for a method getValuePlus12 //with an int return value and one int argument13 int getValuePlus(int userdefined)14 {15 // return keyword returns the expression to the16 // int returnvalue of the calling method,17 // getValuePlus18 return (value + userdefined);19 }20 }

Page 127: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 4, slide 15 of 31Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Case Study

• When the Customer class is instantiated, then theinitialize method on line 8 could be called whichwill invoke the setShipTo method on line 10, passingthe addr to set the shipTo attribute.

1 package OrderEntry;2 import OrderSupport.Person;3 import OrderSupport.Address;45 public class Customer extends Person {6 private Address shipTo;78 public void initialize(Address addr) {9 homeAddress = addr;10 setShipTo(addr);11 }1213 public Address getShipTo(){}14 public void setShipTo(Address addr){}15 }

Page 128: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 4, slide 16 of 31Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Case Study

• The Person class is provided to remind you that theattribute homeAddress is part of the Person class and isthus part of the Customer class based on inheritance.

1 package OrderSupport;2 public abstract class Person {3 private String firstName;4 private String lastName;5 private String initial;6 private int ID;7 private Address homeAddress;89 public String getName(){return firstName;}10 public void setFirstName(String fName){}11 public void setLastName(String lName){}12 public void setInitial(String init){}13 public int getID(){return ID;}14 public void setID(String id){}15 public Address getAddress(){return homeAddress;}16 public void setAddress(Address addr){}17 }

Page 129: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 4, slide 17 of 31Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Method Overloading

• Method overloading is two or more methods in the sameclass with the same name but different arguments.

• Combination of name and arguments is a method’ssignature.

Page 130: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 4, slide 18 of 31Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, December 2000, Revision A.3

Using MethodOverloading

1 class Example2 {3 public static void main (String args[])4 {5 StoreVal store = new StoreVal();6 store.setValue(9);7 int i = store.getValuePlus(2);8 double d = store.getValuePlus(3.6);9 }10 }11 class StoreVal12 {13 int value;14 void setValue(int val)15 {16 value = val;17 }18 int getValuePlus(int more)19 {20 return (value + more);21 }22 double getValuePlus(double more)23 {24 return (value + more);25 }26 }

Page 131: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 4, slide 19 of 31Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Case Study

Discussion – What methods would it be useful to overload inthe order-entry system?

Page 132: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 4, slide 20 of 31Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Constructors

• Constructors are methods that allow you to have morecontrol when you initialize objects.

• Constructors conform to all the rules for methods,except:

• Constructors have no return type.

• The name of a constructor is always the same as thename of the class.

Page 133: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 4, slide 21 of 31Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Writing a Constructor• Include the constructor name without arguments

within the class statement:

class_declaration{ constructor_name ([arguments]) { [ variable_initialization_statements ]; }}

1 class Shirt2 {3 String type;45 // Shirt() is the constructor6 Shirt()7 {8 type = "Oxford Shirt";9 }10}

Page 134: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 4, slide 22 of 31Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Using a Constructor

• To use a constructor to instantiate an object, use thefollowing syntax:

class_name reference_variable = newconstructor ([ arguments ])

• Example: Uses constructor from previous example toinstantiate a reference type myShirt (reference to Shirtobject)

Shirt myShirt = new Shirt() ;

• Example: Uses a different constructor, Shirt(StringdifferentType) , which has one String argument

Shirt myShirt = new Shirt ("Dress Shirt");

Page 135: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 4, slide 23 of 31Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Overloading Constructors

• Constructors can be overloaded like other methods.

• Example:

• Create a new Shirt object using the first constructor,Shirt()

Shirt my Shirt = new Shirt ();

• Create a new Shirt object with the type DressShirt , using the second constructor, Shirt (StringdifferentType)

Shirt my Shirt = new Shirt ("Dress Shirt");

Page 136: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 4, slide 24 of 31Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Overloading Constructors

1 class Shirt2 {3 String type;45 // Shirt() is the first constructor6 Shirt()7 {8 type = "Oxford Shirt";9 }1011 // Shirt(String differentType) is another

// constructor12 Shirt(String differentType)13 {14 type = differentType;15 }16}

Page 137: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 4, slide 25 of 31Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

The Default Constructor

• All classes must have at least one constructor, called thedefault constructor.

1 class Sweater2 {3 String name;45 // the default constructor6 public Sweater()7 {8 }9 }

• The compiler inserts the default constructor when youdo not provide one of your own.

• If you do provide a constructor (whatever its signature)the compiler will not provide the default one.

Page 138: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 4, slide 26 of 31Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, December 2000, Revision A.3

Case Study

The initialize method on line 8 wasoriginally created so that the shipTo addressis initialized when the Customer isinstantiated.

This can be done more easily by replacingthe initialize method with theconstructor on line 13.

1 package OrderEntry;2 import OrderSupport.Person;3 import OrderSupport.Address;45 public class Customer extends Person {6 private Address shipTo;78 // public void initialize(Address addr) {9 // homeAddress = addr;10 // setShipTo(addr);11 // }1213 Customer() {14 setShipTo(homeAddress);15 }1617 public Address getShipTo() {}18 public void setShipTo(Address addr){}19 }

Page 139: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 4, slide 27 of 31Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Coding Structure

• Methods are written in a series of statements; eachstatement ends with a semicolon (;).

• Code structure boundaries are marked with braces ({}).

• Methods and variables for a class must be declaredwithin the class statement.

• Whitespaces (spaces, tabs and linefeeds) do not affect aprogram, so you can use them to organize thestatements.

Page 140: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 4, slide 28 of 31Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Module Summary

• Method

• Recursion

• main

• Arguments

• this

• Overloading

• Constructor

• static

Page 141: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 4, slide 29 of 31Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Exercise: Develop Methods andConstructors

• Exercise objective

• Preparation

• Tasks

• Exercise summary

Page 142: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 4, slide 30 of 31Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Check Your Progress

• Define class behavior using methods

• Declare a public method for encapsulation

• Pass arguments to a method

• Describe a method’s signature

• Explain how method overloading works

• Use a constructor to instantiate an object

Page 143: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 4, slide 31 of 31Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Think Beyond

In order for you to write programs, objects need to interactwith each other. What types of interaction would objects needto do?

Page 144: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology December 2000

Module 5

Object Interaction

Page 145: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 5, slide 2 of 17Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Objectives

• Explain how objects interact with each other throughobject messaging

• Define association

• Define composition

• Decide whether a relationship between two objectsshould be association or composition

• Define the lifetime of an object with regard toassociation and composition

• Define the custody of an object with regard toassociation and composition

Page 146: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 5, slide 3 of 17Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Object Messaging

• One object sends a message to another (the receivingobject).

• The receiving object may send other messages, changeits attribute, or react in any other appropriate way.

• Messaging is handled by operations in the publicinterface of the receiving object.

Page 147: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 5, slide 4 of 17Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, December 2000, Revision A.3

Case Study

• Customer.java source file:

1 package OrderEntry;2 import OrderSupport.Address;3 public class Customer extends Person4 {5 public static void main (String args[])6 {7 Address shipTo = new Address();8 shipTo.printLabel();9 }10 }

• Address.jav a source file:

1 package OrderSupport;2 public class Address3 {4 private String addressLine1;5 private String addressLine2;6 private String city;7 private String state;8 private String postalCode;9 private String country;1011 public void printLabel()12 {13 System.out.println(addressLine1);14 if (addressLine2 != null)15 System.out.println(addressLine2);16 System.out.println(city + “, “ + state +17 postalCode + country);18 }19 }

Page 148: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 5, slide 5 of 17Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Association and Composition

• Objects interact through one of two relationships:association or composition.

• Association: Two independent objects collaborate toachieve some goal, like a person using a computer("uses a" relationship).

• Composition: One object contains another, like apencil that has a lead ("has a" relationship).

• Use containment classes to set up both relationships.

Page 149: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 5, slide 6 of 17Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Case Study

Discussion – In the order-entry system, which classes have anassociation relationship and which have a compositionrelationship?

Page 150: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 5, slide 7 of 17Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Implementing Association andComposition

• Association:

1 class Kitchen2 {3 Stove myStove;4 Refrigerator myRefrigerator;56 public void setStove (Stove aStove)7 {8 myStove = aStove;9 }1011 public void setRefrigerator (Refrigerator aRefrigerator)12 {13 myRefrigerator = aRefrigerator;14 }15 }

Page 151: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 5, slide 8 of 17Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, December 2000, Revision A.3

Implementing Associationand Composition

• Composition:

1 class Seat2 {3 //whatever the class does4 }56 class Wheel7 {8 // whatever the class does9 }1011 class Frame12 {13 // whatever the class does14 }1516 class Car17 {18 Seat mySeat = new Seat();19 Wheel myWheel = new Wheel();20 Frame myFrame = new Frame();21 // and so on22 }

Page 152: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 5, slide 9 of 17Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Choosing Association or Composition

• Consider flexibility, management, and what is right forthe object.

• If the objects ever need to exist independently, useassociation.

Page 153: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 5, slide 10 of 17Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Contrasting Composition andAssociation

Composition Association

Implements the “has a” re-lationship

Implements the “uses a”relationship

Management is simpler,components are createdautomatically

Objects must be createdAssociations and custodymust be established

Inflexible Flexible

Useful when an object hasinterchangeable compo-nents or when an object al-ready exists

Page 154: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 5, slide 11 of 17Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Lifetime of an Object

• Lifetime is the time between when it is created andwhen it is destroyed.

• Composed objects have the same lifetimes.

• Associated objects have overlapping lifetimes.

• Constant association: an object cannot exist or becreated unless another object is always associatedwith it.

Page 155: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 5, slide 12 of 17Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Custody of an Object

• Custody is concerned with the ownership of an objectand the subsequent responsibility to destroy the object.

• Composition: All objects are implicitly in the custody ofthe composite object.

• Association: Requires that the objects’ lifetimes overlap.The creating object has custody, but the custody can bepassed.

Page 156: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 5, slide 13 of 17Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Case Study

Discussion – Who has custody in the Order -Customerrelationship? Who has custody in Customer -Address ?

Page 157: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 5, slide 14 of 17Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Module Summary

• Message passing

• "uses a"

• "has a"

• Object lifetime

• Object custody

• Part/whole relationship

Page 158: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 5, slide 15 of 17Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Exercise: Modeling ObjectRelationships

• Exercise objective

• Preparation

• Tasks

• Exercise summary

Page 159: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 5, slide 16 of 17Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Check Your Progress

• Explain how objects interact with each other throughobject messaging

• Define association

• Define composition

• Decide whether a relationship between two objectsshould be association or composition

• Define the lifetime of an object with regard toassociation and composition

• Define the custody of an object with regard toassociation and composition

Page 160: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 5, slide 17 of 17Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Think Beyond

• How ready do you feel to begin writing a program,based on your identification of objects, attributes andoperations?

• What would you do to explain your analysis to others ifyou are working on the same project with several otherdevelopers?

Page 161: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology December 2000

Module 6

Object-Oriented Analysis and DesignUsing UML

Page 162: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 6, slide 2 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Objectives

• Create a set of use cases to describe a problem domain

• Create a sequence diagram for a use case

• Create a class diagram for a problem domain

• Create an activity diagram for a use case

• Code class declarations for the class diagram

Page 163: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 6, slide 3 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Object-Oriented Analysis and Design

• This module provides a simplified approach to object-oriented analysis and design (OOA/D).

• Unified Modeling Language (UML) is used to notate thedesign.

• UML diagrams covered in this module:

• Use case diagram

• Sequence diagrams

• Class diagrams

• Activity diagrams

Page 164: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 6, slide 4 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Use Case Diagrams

• A use case diagram contains use cases, actors, andrelationship links.

• A use case is an interaction of a user with theapplication in order to achieve a desired result.

• An actor is a role that a user plays when interfacingwith the application.

• Relationship links between use cases are uses andextends.

Page 165: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 6, slide 5 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, December 2000, Revision A.3

Use Case Diagrams

Check levels

Customer

Actor

Use case

Legend

Link

CSR

OEC

Inventorysystem

Assemble order

Warehouse

<<uses>>

Enter order

Out-of-Stock

<<extends>>

Special packaging

<<extends>>

for fragile items

Page 166: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 6, slide 6 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Use Case Diagram Conventions

• Actors on the left represent real people. Actors on theright represent processes or systems.

• Use cases are read from top to bottom and left to right(use this convention in the absence of arrows).

• Each link from an actor to a use case indicates the actorcarries out the process identified by the use case.

• The same actor can be involved in more than one usecase.

Page 167: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 6, slide 7 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Exercise 1: Writing a Use CaseDescription

• Exercise objective

• Tasks

• Exercise summary

Page 168: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 6, slide 8 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Sequence Diagrams

• Capture the operations of a single use case and showhow groups of objects collaborate on those operations

• Exist for each use case

• Contain objects, object lifelines, messages betweenobjects, conditions, iteration markers, activations, andobject deletions

Page 169: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 6, slide 9 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, December 2000, Revision A.3

Sequence Diagram

Order

Window

Order Order

Line

Item

initialize()

initialize()inStock:= check()

*[for each orderline]

[inStock]add()

reorder:= reorder()

Legend

[...] Condition

* Iteration marker X

Activation

Deletion

Object

Message Return

hold()[not inStock]

Payment

verify()

Page 170: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 6, slide 10 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Exercise 2: Creating a SequenceDiagram

• Exercise objective

• Preparation

• Tasks

• Exercise summary

Page 171: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 6, slide 11 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Class Diagram From the ConceptualPerspective

• The class diagram shows object relationships andincludes

• Objects in the application

• Relationships between those objects (associationsand subtypes)

• Relationship multiplicity (one-to-one, and so on)

• Attributes

Page 172: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 6, slide 12 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, December 2000, Revision A.3

Class Diagram From theConceptual Perspective

Order Customer

Order Line Item1*

*

1

1dateReceivedisPrepaid: booleannumber: String

billTo: Address

*

quantity: Integerprice: Money

number: Stringdescription: StringunitPrice: Money

0..1, 1, * Multiplicities

Classes

Legend

Relationships

shipTo: Address

Address2*

PersonEmployee0..1

*11

addressLine1addressLine2citystatepostalCodecountry

IDfirstNamelastNameinitialhomeAddr:

Address

managerdepartmentdependentsSSN

Page 173: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 6, slide 13 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Exercise 3: Creating a Class DiagramFrom the Conceptual Perspective

• Exercise objective

• Tasks

• Exercise summary

Page 174: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 6, slide 14 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Activity Diagrams

• Activity diagrams show objects’ connection withworkflow and how the operations work in parallelprocessing.

• There is one activity diagram for each use case.

• Diagram includes

• Activities

• Activity triggers

• Trigger guards

• Activity synchronization bars

Page 175: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 6, slide 15 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, December 2000, Revision A.3

Activity Diagrams

Enter

Order

Check

Item

* [for each orderline]

[in stock]

Assign

to Order

Dispatch

Order

[out of stock] Hold

Order

[all itemsassigned

[...]Activity

Trigger

Guard

Synchronization bar

Legend

VerifyPayment

[failed]Cancel

Order

and paymentsverified]

[succeeded]

Page 176: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 6, slide 16 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Exercise 4: Creating an ActivityDiagram

• Exercise objective

• Tasks

• Exercise summary

Page 177: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 6, slide 17 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Class Diagram From the SpecificationPerspective

• The specification perspective of the class diagram isconcerned with the interfaces of the application.

• Responsibilities and operations are added.

Page 178: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 6, slide 18 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, December 2000, Revision A.3

Class Diagram From theSpecification Perspective

Order Customer

Order Line Item1*

*

1

1dateReceivedisPrepaid: booleannumber: String

billTo: Address

*

quantity: Integerprice: Money

number: Stringdescription: StringunitPrice: Money

0..1, 1, * Multiplicities

Classes

Legend

Relationships

shipTo: Address

Address2*

PersonEmployee0..1

*11

addressLine1addressLine2citystatepostalCodecountry

IDfirstNamelastNameinitialhomeAddr:

Address

managerdepartmentdependentsSSN

promote()

name

shipOrder() verifyCredit()

Page 179: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 6, slide 19 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Module Summary

• Use cases

• Sequence diagrams

• Activity diagrams

• Class diagrams

• Difference between the conceptual and specificationperspectives

Page 180: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 6, slide 20 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Exercise 5: Creating a Class DiagramFrom the Specification Perspective

• Exercise objective

• Tasks

• Exercise summary

Page 181: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 6, slide 21 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Check Your Progress

• Create a set of use cases to describe a problem domain

• Create a sequence diagram for a use case

• Create a class diagram for a problem domain

• Create an activity diagram for a use case

• Code class declarations for the class diagram

Page 182: SL210_OH

Sun Educational Services

Migrating to OO Programming With Java Technology Module 6, slide 22 of 22Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3

Think Beyond

Now that you have the OO concepts and Java programminglanguage basics, you are ready to proceed with your trainingin the Java programming language. What should your nextstep be?

Page 183: SL210_OH

Implementing Java Security iCopyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000 Revision A.3

Course Contents

About This Course .......................................................................................................Preface-1Course Goal .................................................................................................................................. Preface-2Course Overview ......................................................................................................................... Preface-3Course Expectations .................................................................................................................... Preface-4Course Map ................................................................................................................................... Preface-5Module-by-Module Overview ................................................................................................... Preface-6Course Objectives ......................................................................................................................... Preface-7Skills Gained by Module ............................................................................................................. Preface-9Guidelines for Module Pacing ................................................................................................. Preface-10Topics Not Covered ................................................................................................................... Preface-11How Prepared Are You? ........................................................................................................... Preface-12Introductions .............................................................................................................................. Preface-13How to Use Course Materials .................................................................................................. Preface-14Icons ............................................................................................................................................. Preface-15Typographical Conventions ..................................................................................................... Preface-16Syntax Conventions ................................................................................................................... Preface-17

Objects .....................................................................................................................................1-1Objectives ................................................................................................................................................. 1-2Overview of Object Orientation ............................................................................................................ 1-3Abstraction ............................................................................................................................................... 1-4Functional Abstraction ........................................................................................................................... 1-5Data Abstraction ..................................................................................................................................... 1-6Identifying Objects .................................................................................................................................. 1-7Case Study ................................................................................................................................................ 1-9Identifying Object Attributes and Operations .................................................................................. 1-10

Page 184: SL210_OH

Sun Educational Services

Implementing Java Security iiCopyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000 Revision A.3

Case Study .............................................................................................................................................. 1-11Testing an Identified Object ................................................................................................................ 1-12Relevance to the Problem Domain ..................................................................................................... 1-13Case Study .............................................................................................................................................. 1-14Independent Existence ......................................................................................................................... 1-15Case Study .............................................................................................................................................. 1-16Attributes and Operations ................................................................................................................... 1-17Encapsulation ........................................................................................................................................ 1-19Parts of an Encapsulated Object ......................................................................................................... 1-20Implementing Encapsulation .............................................................................................................. 1-21Case Study .............................................................................................................................................. 1-22Module Summary ................................................................................................................................. 1-23Exercise: Identifying Objects ............................................................................................................... 1-24Check Your Progress ............................................................................................................................ 1-25Think Beyond ........................................................................................................................................ 1-26

Classes ......................................................................................................................................2-1Objectives ................................................................................................................................................. 2-2Class Overview ........................................................................................................................................ 2-3Case Study ................................................................................................................................................ 2-4Generalization ......................................................................................................................................... 2-5Case Study ................................................................................................................................................ 2-6Inheritance ................................................................................................................................................ 2-8Case Study ................................................................................................................................................ 2-9Specialization ......................................................................................................................................... 2-10Polymorphism ....................................................................................................................................... 2-11Another Example .................................................................................................................................. 2-12Case Study .............................................................................................................................................. 2-13Key Points of Polymorphism .............................................................................................................. 2-14Abstract Classes ..................................................................................................................................... 2-15

Page 185: SL210_OH

Sun Educational Services

Implementing Java Security iiiCopyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000 Revision A.3

Another Example .................................................................................................................................. 2-16Case Study .............................................................................................................................................. 2-17Key Points of Abstract Classes ............................................................................................................ 2-18Module Summary ................................................................................................................................. 2-19Exercise: Grouping Objects in Classes ............................................................................................... 2-20Check Your Progress ............................................................................................................................ 2-21Think Beyond ........................................................................................................................................ 2-22

Using Java Classes .................................................................................................................3-1Objectives ................................................................................................................................................. 3-2Declaring Classes .................................................................................................................................... 3-4Case Study ................................................................................................................................................ 3-5Variables ................................................................................................................................................... 3-6Identifiers ................................................................................................................................................. 3-7Java Primitive Types and Reference Types ......................................................................................... 3-9Integral Types ........................................................................................................................................ 3-11Floating Point Types ............................................................................................................................. 3-12Textual Type: char .........................................................3-13Logical Type: boolean ......................................................3-14Object References .................................................................................................................................. 3-15Strings ..................................................................................................................................................... 3-17Case Study .............................................................................................................................................. 3-18Encapsulation ........................................................................................................................................ 3-19Case Study .............................................................................................................................................. 3-20Inheritance .............................................................................................................................................. 3-21Using Inheritance .................................................................................................................................. 3-22Testing Inheritance ............................................................................................................................... 3-24Case Study .............................................................................................................................................. 3-27Containment Classes ............................................................................................................................ 3-28Testing Containment ............................................................................................................................ 3-29

Page 186: SL210_OH

Sun Educational Services

Implementing Java Security ivCopyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000 Revision A.3

Case Study .............................................................................................................................................. 3-30Abstract Classes and Inheritance ........................................................................................................ 3-31Using Abstract Classes ......................................................................................................................... 3-32Case Study .............................................................................................................................................. 3-33Classes and Packages ........................................................................................................................... 3-34Java 2 Platform Class Library Packages ............................................................................................. 3-35Grouping Classes in Packages ............................................................................................................ 3-36Case Study .............................................................................................................................................. 3-37Using Classes Stored in Packages ....................................................................................................... 3-38Coding Structure ................................................................................................................................... 3-39Case Study .............................................................................................................................................. 3-40Module Summary ................................................................................................................................. 3-41Exercise: Implementing the Class Diagram ...................................................................................... 3-43Check Your Progress ............................................................................................................................ 3-44Think Beyond ........................................................................................................................................ 3-46

Using Java Methods ...............................................................................................................4-1Objectives ................................................................................................................................................. 4-2Method Overview ................................................................................................................................... 4-3Why Are Methods Necessary? .............................................................................................................. 4-4Declaring Methods .................................................................................................................................. 4-5Case Study ................................................................................................................................................ 4-6Invoking Methods ................................................................................................................................... 4-7Case Study ................................................................................................................................................ 4-8Object Methods ........................................................................................................................................ 4-9static Methods .................................................................................................................................... 4-10Case Study .............................................................................................................................................. 4-11The this Reference ............................................................................................................................... 4-12Passing Arguments ............................................................................................................................... 4-13Case Study .............................................................................................................................................. 4-15

Page 187: SL210_OH

Sun Educational Services

Implementing Java Security vCopyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000 Revision A.3

Method Overloading ............................................................................................................................ 4-17Using Method Overloading ................................................................................................................. 4-18Case Study .............................................................................................................................................. 4-19Constructors ........................................................................................................................................... 4-20Writing a Constructor ........................................................................................................................... 4-21Using a Constructor .............................................................................................................................. 4-22Overloading Constructors ................................................................................................................... 4-23The Default Constructor ...................................................................................................................... 4-25Case Study .............................................................................................................................................. 4-26Coding Structure ................................................................................................................................... 4-27Module Summary ................................................................................................................................. 4-28Exercise: Develop Methods and Constructors .................................................................................. 4-29Check Your Progress ............................................................................................................................ 4-30Think Beyond ........................................................................................................................................ 4-31

Object Interaction ..................................................................................................................5-1Objectives ................................................................................................................................................. 5-2Object Messaging .................................................................................................................................... 5-3Case Study ................................................................................................................................................ 5-4Association and Composition ............................................................................................................... 5-5Case Study ................................................................................................................................................ 5-6Implementing Association and Composition ..................................................................................... 5-7Choosing Association or Composition ................................................................................................ 5-9Contrasting Composition and Association ....................................................................................... 5-10Lifetime of an Object ............................................................................................................................. 5-11Custody of an Object ............................................................................................................................ 5-12Case Study .............................................................................................................................................. 5-13

Page 188: SL210_OH

Sun Educational Services

Implementing Java Security viCopyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000 Revision A.3

Module Summary ................................................................................................................................. 5-14Exercise: Modeling Object Relationships .......................................................................................... 5-15Check Your Progress ............................................................................................................................ 5-16Think Beyond ........................................................................................................................................ 5-17

Object-Oriented Analysis and Design Using UML ..........................................................6-1Objectives ................................................................................................................................................. 6-2Object-Oriented Analysis and Design .................................................................................................. 6-3Use Case Diagrams ................................................................................................................................. 6-4Use Case Diagram Conventions ........................................................................................................... 6-6Exercise 1: Writing a Use Case Description ........................................................................................ 6-7Sequence Diagrams ................................................................................................................................. 6-8Exercise 2: Creating a Sequence Diagram ......................................................................................... 6-10Class Diagram From the Conceptual Perspective ............................................................................ 6-11Exercise 3: Creating a Class Diagram From the Conceptual Perspective ..................................... 6-13Activity Diagrams ................................................................................................................................. 6-14Exercise 4: Creating an Activity Diagram ......................................................................................... 6-16Class Diagram From the Specification Perspective ......................................................................... 6-17Module Summary ................................................................................................................................. 6-19Exercise 5: Creating a Class Diagram From the Specification Perspective ................................... 6-20Check Your Progress ............................................................................................................................ 6-21Think Beyond ........................................................................................................................................ 6-22