Escolar Documentos
Profissional Documentos
Cultura Documentos
Migrating to OO Programming
With Java Technology
SL-210
December 2000
Preface
About This Course
December 2000
Course Goal
This course provides the necessary concepts for developers
with a non-object-oriented background to begin the move to
Java technology.
This is not a Java technology programming course; it is a
preparatory course that provides the necessary knowledge for
taking SL-275: Java Programming Language.
Preface, slide 2 of 17
Course Overview
Object-oriented analysis and design
Basic syntax for Java technology classes ("Java classes")
and structure of Java technology programs ("Java
programs")
Unified Modeling Language (UML) notation
Preface, slide 3 of 17
Course Expectations
This is not a programming course; no computers will be
used.
OO is a new paradigm and cannot be related to prior
non-OO programming experience.
Preface, slide 4 of 17
Course Map
Preface, slide 5 of 17
Copyright 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 Design
Using UML"
Preface, slide 6 of 17
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
Preface, slide 7 of 17
Course Objectives
Define methods for a class
Describe basic Java technology programming structure
guidelines
Implement the understanding gained through OO and
Java technology syntax by developing UML diagrams
to analyze a problem domain
Preface, slide 8 of 17
Module
Skills Gained
Skill or Objective 1
Skill or Objective 2
Skill or Objective 3
Skill or Objective 4
Preface, slide 9 of 17
Day 1
A.M.
Objects
A.M.
Classes
A.M./P.M.
P.M.
Day 2
A.M.
Object Interaction
A.M./P.M.
Day 3
A.M./P.M.
Preface, slide 10 of 17
Preface, slide 11 of 17
Preface, slide 12 of 17
Introductions
Name
Company affiliation
Title, function, and job responsibility
Programming experience
Reasons for enrolling in this course
Expectations for this course
Preface, slide 13 of 17
Preface, slide 14 of 17
Icons
Demonstration
Reference
Discussion
Exercise
Preface, slide 15 of 17
Typographical Conventions
Typeface or
Symbol
Meaning
Example
AaBbCc123
AaBbCc123
AaBbCc123
Command-line placeholder
replace with a real value
AaBbCc123
Preface, slide 16 of 17
Syntax Conventions
Syntax and example
type variable_identifier
int myFirstVariable;
Variables in italics
Preface, slide 17 of 17
Module 1
Objects
December 2000
Objectives
Describe abstraction and how it is used in object
orientation
Identify objects and non-objects from a problem domain
Describe object encapsulation
Module 1, slide 2 of 26
Module 1, slide 3 of 26
Abstraction
Is the process of ignoring details to concentrate on
essential characteristics
Is the primary means of coping with complexity
Simplifies users interaction with abstracted objects
Has two types: functional abstraction and data
abstraction
Module 1, slide 4 of 26
Functional Abstraction
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;
Unabstracted function
Module 1, slide 5 of 26
Data Abstraction
Deals with data types
Allows details of the internal representation of a data
type to be ignored
Involves functional abstraction
Module 1, slide 6 of 26
Identifying Objects
Object can be a sentence, bank account, number, or car
Objects are
Things
Real or imaginary
Simple or complex
Module 1, slide 7 of 26
Identifying Objects
Satellite dish
Employee
Painters palette
X + Yi
Complex number
Bank account
Bicycle
Example objects
Module 1, slide 8 of 26
Case Study
DirectClothing, Inc. nouns
catalog
clothing
subscribers
closeout items
normal items
order
customer
supplier
payment
warehouse
credit card
order entry
mail order
fax order
online order
inventory
back-ordered
items
system
Internet
business
year
month
order form
check
Module 1, slide 9 of 26
Module 1, slide 10 of 26
Case Study
For the Order object, the following attributes and
operations could be defined:
Attributes: orderNumber, customerNumber,
dateOrdered, amountOwed
Operations: whatCustomer, calcAmountOwed,
printOrder, payOrder
Discussion What would be the attributes and
operations for the Customer object?
Module 1, slide 11 of 26
Module 1, slide 12 of 26
Module 1, slide 13 of 26
Case Study
The Order object passes the relevance test:
Exists within the boundaries of the problem
statement
Is required for the system to fulfill its responsibilities
Is required as part of an interaction between a user
and the system
Discussion Test the other candidate objects in the case
study.
Module 1, slide 14 of 26
Independent Existence
To be an object and not a characteristic of another object,
the object must need to exist independently.
Module 1, slide 15 of 26
Case Study
Can an Order object exist without any of the other
objects? It can, but it must have an associated Customer
object.
Address could be an attribute of Customer, but in this
case study it is advantageous for Address to be a
separate object.
Discussion Are there any other objects in the case
study that need to exist independently?
Module 1, slide 16 of 26
Module 1, slide 17 of 26
Case Study
The Order object has many attributes and operations
defined as do most of the candidate objects.
Are there any objects listed on page 1-10 that do not
have attributes and operations?
Module 1, slide 18 of 26
Encapsulation
Encapsulation separates the external aspects of an object
from the internal implementation details.
Internal changes need not affect external interface.
Module 1, slide 19 of 26
Module 1, slide 20 of 26
Implementing Encapsulation
An objects 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 be
changed or accessed only through public operations.
Module 1, slide 21 of 26
Case Study
Using the Order object from the case study, you would
make all attributes private and need to create public
operations to get and set values for each of the
attributes.
All other operations, such as calcAmountOwed and
payOrder, would also be public.
However, you could decide that the calcAmountOwed
should be private so other objects cannot have access to
calculate the amount owed.
Discussion How would you encapsulate the Customer
object?
Module 1, slide 22 of 26
Module Summary
Object
Attributes
Operations
Abstraction
Data hiding
Encapsulate
Member
Module 1, slide 23 of 26
Module 1, slide 24 of 26
Module 1, slide 25 of 26
Think Beyond
What if you have several objects in a system that share
many characteristics but are different, such as different
types of musical instruments?
How would you write them or categorize them to
promote reuse?
Module 1, slide 26 of 26
Module 2
Classes
December 2000
Objectives
Group objects with similar attributes and common
operations in classes
Explain how classes are used to define objects
Define inheritance and explain how it relates to
software reuse
Define generalization and specialization and how they
relate to inheritance
Define polymorphism and explain how inheritance
promotes polymorphism
Define abstract classes
Migrating to OO Programming With Java Technology
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3
Module 2, slide 2 of 22
Class Overview
Objects of
a Leaf class
Objects of a
Ball class
Module 2, slide 3 of 22
Case Study
For each object identified in the order entry system, define a
corresponding class.
Module 2, slide 4 of 22
Generalization
Example: Transport is a generalization of several classes
that provide transportation.
Generalization identifies and defines the common
attributes and operations in a collection of objects.
Module 2, slide 5 of 22
Case Study
The order entry clerk and customer service
representative objects are considered identical and an
Employee class will be created. You can create a
CustomerServiceRepresentative or an OrderEntryClerk
object from the Employee class.
The Customer object and the Employee class also have
similarities. You could create a Person class that would
contain those similar attributes; you could also create an
Address class.
Discussion What other generalizations can you find in
the objects?
Module 2, slide 6 of 22
Inheritance
Example: Soccer Ball class can inherit members from a Ball
class.
Superclass
Subclasses
Basketball
Ball
Soccer Ball
Baseball
Module 2, slide 7 of 22
Inheritance
Is a mechanism for defining a new class in terms of an
existing class
Allows you to group related classes so that they can be
managed collectively
Promotes reuse
Allows you to hide or override inherited members
Relevant terms: generalization, specialization, override
Module 2, slide 8 of 22
Case Study
Both the Customer and Employee classes
extend Person.
attributes
ID
firstName
lastName
initial
methods
getName
Person
Customer
attributes
ID
firstName
lastName
initial
*salutation
methods
getName
getSalutation
attributes
ID
firstName
lastName
initial
*SSN
methods
getName
getSSN
grantRaise
Employee
OE Clerk
CS Rep.
Module 2, slide 9 of 22
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, December 2000, Revision A.3
Specialization
Generalized
class:
Classes:
Automobile
Transport
Bicycle
Plane
Commercial
Specialized
classes:
Car
Truck
Mountain
Road
Private
Module 2, slide 10 of 22
Polymorphism
Allows you to implement an inherited operation in a
subclass
Works only when the common operation gives the same
semantic result
Implementation of a polymorphic function depends on
the object it is applied to
Can be used only with inheritance
Module 2, slide 11 of 22
Another Example
Consider a general class called WritingInstrument
The class has an operation called write
What are examples of objects in the classroom that
could be subclasses of WritingInstrument?
How is the write operation polymorphic?
Module 2, slide 12 of 22
Case Study
In the order-entry system, you could use polymorphism
with the Person objects giveName operation. Use it as
is for the Employee object, but all Customers would
give the salutation that should be used with their name,
in addition.
Discussion What other operations could be
polymorphic?
Module 2, slide 13 of 22
Module 2, slide 14 of 22
Abstract Classes
A class with at least one abstract operation is an abstract
class.
A subclass of an abstract class needs to provide an
implementation of all abstract operations or it is also an
abstract class.
An abstract class cannot be instantiated (you cannot
create objects of an abstract class).
Operations in an abstract class are placeholders.
Module 2, slide 15 of 22
Another Example
Consider implementing classes for a circle, rectangle,
and triangle.
Operations for these classes must include setColor and
setBorderStyle.
You decide to create an abstract class called share with
two abstract operations: setColor and setBorderStyle
The subclasses must override these abstract operations
and provide implementation code that makes sense for
the subclass shape.
Module 2, slide 16 of 22
Case Study
The Person object in the order-entry system is an
abstract class; you would instantiate a customer or an
employee, but not a person.
Discussion What other abstract classes could you
use in an order-entry system?
Module 2, slide 17 of 22
Module 2, slide 18 of 22
Module Summary
Class
Object
Generalization
Inheritance
Overriding
Specialization
Polymorphism
Abstract class
Module 2, slide 19 of 22
Module 2, slide 20 of 22
Module 2, slide 21 of 22
Think Beyond
What components would need to be specified in a Java
programming language statement to describe a class?
Module 2, slide 22 of 22
Module 3
Using Java Classes
December 2000
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 to
Java programming language guidelines
Use inheritance correctly
Use abstract classes
Module 3, slide 2 of 46
Objectives
Use the import statement to include classes in a
program
Use the package statement to group classes in a class
hierarchy
Understand the structure of a Java program
Module 3, slide 3 of 46
Declaring Classes
[class_modifier] class class_identifier
{block}
Module 3, slide 4 of 46
Case Study
Code an Order class for the order-entry program like
this:
public class Order { }
Module 3, slide 5 of 46
Variables
Variable is the Java programming language term for
attributes.
Each must have type and unique identifier.
Module 3, slide 6 of 46
Identifiers
Identifiers are names assigned to classes, variables, and
methods.
The first character must be one of the following:
An uppercase letter (AZ)
A lowercase letter (az)
The underscore character (_)
The dollar character ($)
Module 3, slide 7 of 46
Identifiers
The second and subsequent characters of an identifier
must be any of the following:
Any character from previous list
Numeric characters (09)
In multiple-word identifiers, start each subsequent
word with a capital letter.
Java keywords may not be used.
The Java programming language is case sensitive.
Module 3, slide 8 of 46
Module 3, slide 9 of 46
byte
short
int
long
float
double
char
boolean
Module 3, slide 10 of 46
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
int
32 bits
long
64 bits
Module 3, slide 11 of 46
Float Length
32 bits
64 bits
Module 3, slide 12 of 46
Module 3, slide 13 of 46
Module 3, slide 14 of 46
Object References
Hold a handle of an object
Can only refer to objects of the declared type or of a
subclass type
Module 3, slide 15 of 46
Object References
Declaring an object reference:
type variable_identifier
Computer laptop;
Creating objects:
variable_identifier = new class_name
laptop = new Computer();
Module 3, slide 16 of 46
Strings
Reference type used to store a sequence of characters
Creating Strings:
Method 1
String variable_identifier = new String
"string_value");
String animal = new String("dog");
Method 2
String variable = "string_value";
String animal = "dog";
Migrating to OO Programming With Java Technology
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3
Module 3, slide 17 of 46
Case Study
The Person class declaration with the variables defined
would appears as shown:
1
2
3
4
5
6
7
8
class Person
{
String firstName;
String lastName;
String initial;
String ID;
Address homeAddress
}
Module 3, slide 18 of 46
Encapsulation
Encapsulation hides implementation from users
All variables are should be private (hidden in
implementation)
Private variables can be accessed only through public
methods (operations)
Module 3, slide 19 of 46
Case Study
The following class demonstrates making all variables private
and making the operations public:
1 class Person
2 {
3
private String firstName;
4
private String lastName;
5
private String initial;
6
private int ID;
7
private Address homeAddress;
8
9
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 }
Migrating to OO Programming With Java Technology
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3
Module 3, slide 20 of 46
Inheritance
Example: Manager and Engineer classes both have
characteristics of an Employee.
Common items are defined in one class and subsequent
classes base themselves on that class.
Module 3, slide 21 of 46
Using Inheritance
Declaration of Manager and Engineer
classes:
1 class Manager
2 {
3
int employeeNumber;
4
String name;
5
int departmentNumber;
6
int extensionNumber;
7
int salary;
8
int numberOfWorkers;
9
// and so on
10 }
1 class Engineer
2 {
3
int employeeNumber;
4
String name;
5
int departmentNumber;
6
int extensionNumber;
7
int salary;
8
Manager worksFor;
9
// and so on
10 }
Module 3, slide 22 of 46
Copyright 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
2
3
4
5
6
7
8
9
class Employee
{
int employeeNumber;
String name;
int departmentNumber;
int extensionNumber;
int salary;
// and so on
}
1
2
3
4
5
6
7
8
9
10
11
Module 3, slide 23 of 46
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, December 2000, Revision A.3
Testing Inheritance
In the Java programming language, a class can inherit
from only one superclass at a time.
It is very important to use inheritance only if it is valid
or unavoidable.
Check validity using the is a phrase (a Manager is an
Employee).
Module 3, slide 24 of 46
Testing Inheritance
Class declaration with duplication:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Cycle
{
int numberOfWheels;
int numberOfSeats;
float luggageCapacity;
// and so on
}
class Boeing747
{
int numberOfWheels;
int numberOfSeats;
float luggageCapacity;
int numberOfWings;
// and so on
}
class Cycle
{
int numberOfWheels;
int numberOfSeats;
float luggageCapacity;
// and so on
}
class Boeing747 extends Cycle
{
int numberOfWings;
// and so on
}
Module 3, slide 25 of 46
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, December 2000, Revision A.3
Testing Inheritance
Correct use of inheritance:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Vehicle
{
int numberOFWheels;
int numberOfSeats;
float luggageCapacity;
// and so on
}
class Cycle extends Vehicle
{
// and so on
}
class Boeing747 extends Vehicle
{
int numberOfWings;
// and so on
}
Module 3, slide 26 of 46
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, December 2000, Revision A.3
Case Study
Remember the example of the Customer and Employee
classes; you could code the following class declarations
for inheritance:
class Customer extends Person {}
class Employee extends Person {}
Module 3, slide 27 of 46
Containment Classes
Example: Kitchen class can be used to contain Stove
and Refrigerator classes
1 class Stove
2 {
3
//whatever the class does
4 }
5
6 class Refrigerator
7 {
8
// whatever the class does
9 }
10
11class Kitchen
12{
13 Stove myStove;
14 Refrigerator myRefrigerator;
15 // and so on
16}
Module 3, slide 28 of 46
Testing Containment
Use the "has a" phrase to test containment validity (a
Kitchen has a Stove; a Kitchen has a Refrigerator)
Module 3, slide 29 of 46
Case Study
The Person class is a containment
class because it contains the home
address of the person.
1 class Person
2 {
3
private String firstName;
4
private String lastName;
5
private String initial;
6
private int ID;
7
private Address homeAddress;
8
9
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 }
Module 3, slide 30 of 46
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, December 2000, Revision A.3
Module 3, slide 31 of 46
Module 3, slide 32 of 46
Case Study
Code an abstract class Person:
1 public abstract class Person
2 {
3
private String firstName;
4
private String lastName;
5
private String initial;
6
private int ID;
7
private Address homeAddress;
8
9
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 }
Module 3, slide 33 of 46
Module 3, slide 34 of 46
Module 3, slide 35 of 46
Module 3, slide 36 of 46
Case Study
Discussion What parts of the order-entry system would you
package? Code the package declaration.
Module 3, slide 37 of 46
Module 3, slide 38 of 46
Coding Structure
Java is a free-format programming language with few
rules:
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 in
the source file.
You can have only one public class in a source file.
The Java source file is always named
public_class_name.java; the compiled version is
one or more files named class_name.class.
Migrating to OO Programming With Java Technology
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3
Module 3, slide 39 of 46
Case Study
The following code example shows how to add the class
Customer to the package OrderEntry and import the Person
and Address classes from the OrderSupport package:
1
2
3
package OrderEntry;
import OrderSupport.Person;
import OrderSupport.Address;
Module 3, slide 40 of 46
Module Summary
1. Defines a block that contains all your attributes and
operations.
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 or
false.
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 for
decimal numbers.
Migrating to OO Programming With Java Technology
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3
Module 3, slide 41 of 46
Module 3, slide 42 of 46
Module 3, slide 43 of 46
Module 3, slide 44 of 46
Module 3, slide 45 of 46
Think Beyond
Now that you have written a class in the Java programming
language, how do you write an operation (method)? What
information would you need to provide?
Module 3, slide 46 of 46
Module 4
Using Java Methods
December 2000
Objectives
Define class behavior using methods
Declare a public method for encapsulation
Pass arguments to a method
Describe a methods signature
Explain how method overloading works
Use a constructor to instantiate an object
Module 4, slide 2 of 31
Method Overview
Method is the Java technology term for an OO operation.
Methods separate the statements into code blocks that
can run independently of each other.
Methods can invoke each other.
All programs use methods.
Module 4, slide 3 of 31
Module 4, slide 4 of 31
Declaring Methods
Methods are written inside the body of a class.
Module 4, slide 5 of 31
Case Study
The Person class attributes and
method declarations:
1 public abstract class Person
2 {
3
private String firstName;
4
private String lastName;
5
private String initial;
6
private int ID;
7
private Address homeAddress;
8
9
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 }
Module 4, slide 6 of 31
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, December 2000, Revision A.3
Invoking Methods
object_reference.method_identifier([arguments])
1 class VoidMethodInvocation
2 {
3
public static void main (String args[])
4
{
5
ClassOne one = new ClassOne();
6
one.returnNothing();
7
}
8 }
9
10class ClassOne
11{
12 public void returnNothing()
13 {
14
//whatever the method does
15 }
16}
Module 4, slide 7 of 31
Case Study
Customer.java source file:
1
2
3
4
5
6
7
8
9
10
package OrderEntry;
import OrderSupport.Address;
public class Customer extends Person
{
public static void main (String args[])
{
Adress shipTo = new Address();
shipTo.printLabel();
}
}
package OrderSupport;
public class Address
{
private String addressLine1;
private String addressLine2;
private String city;
private String state;
private String postalCode;
private String country;
public void printLabel()
{
System.out.println(addressLine1);
if (addressLine2 != null)
System.out.println(addressLine2);
System.out.println(city + ", "+ state +
postalCode + country);
}
}
Module 4, slide 8 of 31
Copyright 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 object
and the dot operator (.).
1
2
3
4
5
6
7
8
class MethodInvocation
{
public static void main (String args[])
{
ClassOne one = new ClassOne();
int i = one.returnAnInt();
int j = i * one.returnAnInt() + 6;
System.out.println("An int: " +
one.returnAnInt());
9
}
10 }
11
12 class ClassOne
13 {
14
public int returnAnInt()
15
{
16
return 9;
17
}
18 }
Module 4, slide 9 of 31
static Methods
The static modifier should be used with generic
utilities or methods that may need to be called any time
without first instantiating an object from the class.
1
2
3
4
5
6
7
8
class StaticExample
{
public static void main (string args[])
{
double rand = Math.random();
System.out.println("A random number: " + rand);
}
}
Module 4, slide 10 of 31
Case Study
Discussion What static methods could you use in the orderentry example?
Module 4, slide 11 of 31
Module 4, slide 12 of 31
Passing Arguments
You must give values for any methods with arguments
when invoking the method.
Arguments must be declared as a type-variable pair:
Module 4, slide 13 of 31
Passing Arguments
1 class StoreVal
2 {
3
int value;
4
// method declaration for a method with no
5
// return value and one int argument
6
void setValue(int val)
7
{
8
// the this keyword sets value to val
9
this.value = val;
10
}
11
//method declaration for a method getValuePlus
12
//with an int return value and one int argument
13
int getValuePlus(int userdefined)
14
{
15
// return keyword returns the expression to the
16
// int returnvalue of the calling method,
17
// getValuePlus
18
return (value + userdefined);
19
}
20 }
Module 4, slide 14 of 31
Case Study
When the Customer class is instantiated, then the
initialize method on line 8 could be called which
will invoke the setShipTo method on line 10, passing
the addr to set the shipTo attribute.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package OrderEntry;
import OrderSupport.Person;
import OrderSupport.Address;
public class Customer extends Person {
private Address shipTo;
public void initialize(Address addr) {
homeAddress = addr;
setShipTo(addr);
}
public Address getShipTo(){}
public void setShipTo(Address addr){}
}
Module 4, slide 15 of 31
Case Study
The Person class is provided to remind you that the
attribute homeAddress is part of the Person class and is
thus 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;
8
9
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 }
Module 4, slide 16 of 31
Method Overloading
Method overloading is two or more methods in the same
class with the same name but different arguments.
Combination of name and arguments is a methods
signature.
Module 4, slide 17 of 31
Using Method
Overloading
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Example
{
public static void main (String args[])
{
StoreVal store = new StoreVal();
store.setValue(9);
int i = store.getValuePlus(2);
double d = store.getValuePlus(3.6);
}
}
class StoreVal
{
int value;
void setValue(int val)
{
value = val;
}
int getValuePlus(int more)
{
return (value + more);
}
double getValuePlus(double more)
{
return (value + more);
}
}
Module 4, slide 18 of 31
Copyright 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 in
the order-entry system?
Module 4, slide 19 of 31
Constructors
Constructors are methods that allow you to have more
control 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 the
name of the class.
Module 4, slide 20 of 31
Writing a Constructor
Include the constructor name without arguments
within the class statement:
class_declaration
{
constructor_name([arguments])
{
[variable_initialization_statements];
}
}
1 class Shirt
2 {
3
String type;
4
5
// Shirt() is the constructor
6
Shirt()
7
{
8
type = "Oxford Shirt";
9
}
10}
Module 4, slide 21 of 31
Using a Constructor
To use a constructor to instantiate an object, use the
following syntax:
class_name reference_variable = new
constructor([arguments])
Module 4, slide 22 of 31
Overloading Constructors
Constructors can be overloaded like other methods.
Example:
Create a new Shirt object using the first constructor,
Shirt()
Shirt myShirt = new Shirt();
Create a new Shirt object with the type Dress
Shirt, using the second constructor, Shirt(String
differentType)
Shirt myShirt = new Shirt("Dress Shirt");
Module 4, slide 23 of 31
Overloading Constructors
1 class Shirt
2 {
3
String type;
4
5
// Shirt() is the first constructor
6
Shirt()
7
{
8
type = "Oxford Shirt";
9
}
10
11 // Shirt(String differentType) is another
// constructor
12 Shirt(String differentType)
13 {
14
type = differentType;
15 }
16}
Module 4, slide 24 of 31
Module 4, slide 25 of 31
Case Study
The initialize method on line 8 was
originally created so that the shipTo address
is initialized when the Customer is
instantiated.
This can be done more easily by replacing
the initialize method with the
constructor on line 13.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package OrderEntry;
import OrderSupport.Person;
import OrderSupport.Address;
public class Customer extends Person {
private Address shipTo;
// public void initialize(Address addr) {
// homeAddress = addr;
// setShipTo(addr);
// }
Customer() {
setShipTo(homeAddress);
}
public Address getShipTo() {}
public void setShipTo(Address addr){}
}
Module 4, slide 26 of 31
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, December 2000, Revision A.3
Coding Structure
Methods are written in a series of statements; each
statement ends with a semicolon (;).
Code structure boundaries are marked with braces ({}).
Methods and variables for a class must be declared
within the class statement.
Whitespaces (spaces, tabs and linefeeds) do not affect a
program, so you can use them to organize the
statements.
Module 4, slide 27 of 31
Module Summary
Method
Recursion
main
Arguments
this
Overloading
Constructor
static
Module 4, slide 28 of 31
Module 4, slide 29 of 31
Module 4, slide 30 of 31
Think Beyond
In order for you to write programs, objects need to interact
with each other. What types of interaction would objects need
to do?
Module 4, slide 31 of 31
Module 5
Object Interaction
December 2000
Objectives
Explain how objects interact with each other through
object messaging
Define association
Define composition
Decide whether a relationship between two objects
should be association or composition
Define the lifetime of an object with regard to
association and composition
Define the custody of an object with regard to
association and composition
Migrating to OO Programming With Java Technology
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services December 2000, Revision A.3
Module 5, slide 2 of 17
Object Messaging
One object sends a message to another (the receiving
object).
The receiving object may send other messages, change
its attribute, or react in any other appropriate way.
Messaging is handled by operations in the public
interface of the receiving object.
Module 5, slide 3 of 17
Case Study
Customer.java source file:
1
2
3
4
5
6
7
8
9
10
package OrderEntry;
import OrderSupport.Address;
public class Customer extends Person
{
public static void main (String args[])
{
Address shipTo = new Address();
shipTo.printLabel();
}
}
package OrderSupport;
public class Address
{
private String addressLine1;
private String addressLine2;
private String city;
private String state;
private String postalCode;
private String country;
public void printLabel()
{
System.out.println(addressLine1);
if (addressLine2 != null)
System.out.println(addressLine2);
System.out.println(city + , + state +
postalCode + country);
}
}
Module 5, slide 4 of 17
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, December 2000, Revision A.3
Module 5, slide 5 of 17
Case Study
Discussion In the order-entry system, which classes have an
association relationship and which have a composition
relationship?
Module 5, slide 6 of 17
Module 5, slide 7 of 17
Implementing Association
and Composition
Composition:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Seat
{
//whatever the class does
}
class Wheel
{
// whatever the class does
}
class Frame
{
// whatever the class does
}
class Car
{
Seat mySeat = new Seat();
Wheel myWheel = new Wheel();
Frame myFrame = new Frame();
// and so on
}
Module 5, slide 8 of 17
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, December 2000, Revision A.3
Module 5, slide 9 of 17
Association
Inflexible
Flexible
Useful when an object has
interchangeable components or when an object already exists
Module 5, slide 10 of 17
Lifetime of an Object
Lifetime is the time between when it is created and
when it is destroyed.
Composed objects have the same lifetimes.
Associated objects have overlapping lifetimes.
Constant association: an object cannot exist or be
created unless another object is always associated
with it.
Module 5, slide 11 of 17
Custody of an Object
Custody is concerned with the ownership of an object
and the subsequent responsibility to destroy the object.
Composition: All objects are implicitly in the custody of
the composite object.
Association: Requires that the objects lifetimes overlap.
The creating object has custody, but the custody can be
passed.
Module 5, slide 12 of 17
Case Study
Discussion Who has custody in the Order-Customer
relationship? Who has custody in Customer-Address?
Module 5, slide 13 of 17
Module Summary
Message passing
"uses a"
"has a"
Object lifetime
Object custody
Part/whole relationship
Module 5, slide 14 of 17
Module 5, slide 15 of 17
Module 5, slide 16 of 17
Think Beyond
How ready do you feel to begin writing a program,
based on your identification of objects, attributes and
operations?
What would you do to explain your analysis to others if
you are working on the same project with several other
developers?
Module 5, slide 17 of 17
Module 6
Object-Oriented Analysis and Design
Using UML
December 2000
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
Module 6, slide 2 of 22
Module 6, slide 3 of 22
Module 6, slide 4 of 22
<<uses>>
CSR
Check levels
OEC
<<extends>>
Inventory
system
Out-of-Stock
Assemble order
<<extends>>
Warehouse
Special packaging
for fragile items
Legend
Use case
Link
Actor
Module 6, slide 5 of 22
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, December 2000, Revision A.3
Module 6, slide 6 of 22
Module 6, slide 7 of 22
Sequence Diagrams
Capture the operations of a single use case and show
how groups of objects collaborate on those operations
Exist for each use case
Contain objects, object lifelines, messages between
objects, conditions, iteration markers, activations, and
object deletions
Module 6, slide 8 of 22
Sequence Diagram
Order
Window
Order
Order
Line
Item
Payment
initialize()
*[for each orderline]
initialize()
inStock:= check()
[inStock]
add()
reorder:= reorder()
[not inStock]
hold()
verify()
Legend
Object
[...]
*
Message
Activation
Condition
Iteration marker
Return
Deletion
Module 6, slide 9 of 22
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, December 2000, Revision A.3
Module 6, slide 10 of 22
Module 6, slide 11 of 22
Order
* 1
dateReceived
isPrepaid: boolean
number: String
shipTo: Address
billTo: Address
Employee
0..1
manager
department
dependents
SSN
Address
* 2
addressLine1
addressLine2
city
state
postalCode
country
1
1
Person
ID
firstName
lastName
initial
homeAddr:
Address
Order Line
quantity: Integer
price: Money
Item
*
number: String
description: String
unitPrice: Money
Legend
Classes
0..1, 1, *
Relationships
Multiplicities
Module 6, slide 12 of 22
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, December 2000, Revision A.3
Module 6, slide 13 of 22
Activity Diagrams
Activity diagrams show objects connection with
workflow and how the operations work in parallel
processing.
There is one activity diagram for each use case.
Diagram includes
Activities
Activity triggers
Trigger guards
Activity synchronization bars
Module 6, slide 14 of 22
Activity Diagrams
Enter
Order
[failed]
Verify
Payment
Check
[out of stock]
Item
Hold
Order
[in stock]
Assign
to Order
[succeeded]
[all items
assigned
and payments
verified]
Dispatch
Order
Legend
Activity
Trigger
[...]
Guard
Synchronization bar
Module 6, slide 15 of 22
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, December 2000, Revision A.3
Module 6, slide 16 of 22
Module 6, slide 17 of 22
Order
* 1
dateReceived
isPrepaid: boolean
number: String
shipOrder()
shipTo: Address
billTo: Address
name
verifyCredit()
Employee
0..1
manager
department
dependents
SSN
promote()
Address
* 2
addressLine1
addressLine2
city
state
postalCode
country
1
1
Person
ID
firstName
lastName
initial
homeAddr:
Address
Order Line
quantity: Integer
price: Money
Item
*
number: String
description: String
unitPrice: Money
Legend
Classes
0..1, 1, *
Relationships
Multiplicities
Module 6, slide 18 of 22
Copyright 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 specification
perspectives
Module 6, slide 19 of 22
Module 6, slide 20 of 22
Module 6, slide 21 of 22
Think Beyond
Now that you have the OO concepts and Java programming
language basics, you are ready to proceed with your training
in the Java programming language. What should your next
step be?
Module 6, slide 22 of 22
Course Contents
About This Course .......................................................................................................Preface-1
Course Goal .................................................................................................................................. Preface-2
Course Overview ......................................................................................................................... Preface-3
Course Expectations .................................................................................................................... Preface-4
Course Map ................................................................................................................................... Preface-5
Module-by-Module Overview ................................................................................................... Preface-6
Course Objectives ......................................................................................................................... Preface-7
Skills Gained by Module ............................................................................................................. Preface-9
Guidelines for Module Pacing ................................................................................................. Preface-10
Topics Not Covered ................................................................................................................... Preface-11
How Prepared Are You? ........................................................................................................... Preface-12
Introductions .............................................................................................................................. Preface-13
How to Use Course Materials .................................................................................................. Preface-14
Icons ............................................................................................................................................. Preface-15
Typographical Conventions ..................................................................................................... Preface-16
Syntax Conventions ................................................................................................................... Preface-17
Objects .....................................................................................................................................1-1
Objectives ................................................................................................................................................. 1-2
Overview of Object Orientation ............................................................................................................ 1-3
Abstraction ............................................................................................................................................... 1-4
Functional Abstraction ........................................................................................................................... 1-5
Data Abstraction ..................................................................................................................................... 1-6
Identifying Objects .................................................................................................................................. 1-7
Case Study ................................................................................................................................................ 1-9
Identifying Object Attributes and Operations .................................................................................. 1-10
Classes ......................................................................................................................................2-1
Objectives ................................................................................................................................................. 2-2
Class Overview ........................................................................................................................................ 2-3
Case Study ................................................................................................................................................ 2-4
Generalization ......................................................................................................................................... 2-5
Case Study ................................................................................................................................................ 2-6
Inheritance ................................................................................................................................................ 2-8
Case Study ................................................................................................................................................ 2-9
Specialization ......................................................................................................................................... 2-10
Polymorphism ....................................................................................................................................... 2-11
Another Example .................................................................................................................................. 2-12
Case Study .............................................................................................................................................. 2-13
Key Points of Polymorphism .............................................................................................................. 2-14
Abstract Classes ..................................................................................................................................... 2-15
ii
iii
iv
vi