SL210-211 - Migrating To OO Programming With Java - Oh - 0499
SL210-211 - Migrating To OO Programming With Java - Oh - 0499
Migrating to OO Programming
With Java Technology
SL-210/SL-211
Preface
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/276: Java Programming Language.
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
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.
Object-Oriented Concepts
Objects Classes
Object Relationships
Object Interaction
Object-Oriented Notation
Object-Oriented
Analysis and Design
Using UML
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"
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
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
Module
Skills Gained 1 2 3 4
Skill or Objective 1
Skill or Objective 2
Skill or Objective 3
Skill or Objective 4
Introductions
• Name
• Company affiliation
• Title, function, and job responsibility
• Programming experience
• Reasons for enrolling in this course
• Expectations for this course
Icons
• Demonstration
• Reference
• Discussion
• Exercise
Typographical Conventions
Typeface or
Meaning Example
Symbol
AaBbCc123 The names of commands, files, Edit your .login file.
and directories; Use ls -a to list all files.
on-screen computer output system% You have mail.
AaBbCc123 What you type, contrasted with system% su
on-screen computer output Password:
AaBbCc123 Command-line placeholder— To delete a file, type rm
replace with a real value filename.
AaBbCc123 Book titles, new words or Read Chapter 6 in User’s
terms, or words to be Guide. These are called class
emphasized options.
You must be root to do this.
Syntax Conventions
• Syntax and example
type variable_identifier
int myFirstVariable;
• Variables in italics
Module 1
Objects
Objectives
• Describe abstraction and how it is used in object
orientation
• Identify objects and non-objects from a problem domain
• Describe object encapsulation
Abstraction
• Is the process of ignoring details to concentrate on
essential characteristics
• Is the primary means of coping with complexity
Functional Abstraction
• Unabstracted function
Identifying Objects
• Object can be a sentence, bank account, number, or car
• Objects are
• Things
• Real or imaginary
• Simple or complex
Identifying Objects
X + Yi
Complex number Bank account Bicycle
• Example objects
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?
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.
Independent Existence
• To be an object and not a characteristic of another object,
the object must need to exist independently.
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?
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-9 that do not have
attributes and operations?
Encapsulation
• Encapsulation separates the external aspects of an object
from the internal implementation details.
• Internal changes need not affect external interface.
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 be
changed or accessed only through public operations.
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?
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 2
Classes
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
Class Overview
Objects of Objects of a
a Leaf class Ball class
Case Study
For each object identified in the order entry system, define a
corresponding class.
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.
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?
Inheritance
Example: Soccer Ball class can inherit members from a Ball
class.
Superclass Ball
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
attributes
ID
firstName
lastName
initial
methods
giveName
Person add
remove
attributes
ID
Customer Employee firstName
lastName
attributes initial
ID *SSN
firstName methods
lastName giveName
initial add
*salutation remove
methods OE Clerk CS Rep.
giveName
add
remove
Specialization
Generalized Transport
class:
Specialized Commercial
classes:
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
Case Study
• In the order-entry system, you could use polymorphism
with the Person object’s 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?
Abstract Classes
• Abstract classes define the attributes and operations
that must be implemented.
• Abstract classes provide a default operation definition
and expect every subclass to provide its own actions to
be performed for the operation defined.
• Operations in an abstract class are placeholders.
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.
Think Beyond
• What components would need to be specified in a Java
programming language statement to describe a class?
Module 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 to
Java programming language guidelines
• Use inheritance correctly
• Use abstract classes
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
Declaring Classes
[class_modifier] class class_identifier
{block}
Case Study
• Code an Order class for the order-entry program like
this:
class Order { }
Variables
• Variable is the Java programming language term for
attributes.
• Each must have type and unique identifier.
Identifiers
• Identifiers are names assigned to classes, variables, and
methods.
• 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 ($)
Identifiers
• The second and subsequent characters of an identifier
must be any of the following:
• Any character from previous list
• Numeric characters (0–9)
• 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.
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
Reference Types
• Is used to store the address of an object
• Can store only one reference type: a reference to an
object or the type of the subclass or superclass
Strings
• Reference type used to store a sequence of characters
• Creating Strings:
• Method 1
String variable_identifier = new String
"string_value");
• Method 2
String variable = "string_value";
Case Study
• The Person class declaration with the variables defined
would appears as shown:
1 class Person
2 {
3 String firstName;
4 String lastName;
5 String initial;
6 String ID;
7 Address homeAddress
8 }
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)
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 }
Inheritance
• Example: Manager and Clerk classes both have
characteristics of an Employee.
• Common items are defined in one class and subsequent
classes base themselves on that class.
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 }
• Example:
1 class Employee
2 {
3 int employeeNumber;
4 String name;
5 int departmentNumber;
6 int extensionNumber;
7 int salary;
8 // and so on
9 }
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”).
Case Study
• Remember the example of the Customer and Employee
classes; you could code the following class declarations
for inheritance:
class Customer extends Person {}
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}
Testing Containment
• Use the "has a" phrase to test containment validity (a
Kitchen has a Stove; a Kitchen has a Refrigerator)
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 }
Case Study
Discussion – What parts of the order-entry system would you
package? Code the package declaration.
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.
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 OrderEntry package:
1 package OrderEntry;
2 import OrderEntry.Person;
3 import OrderEntry.Address;
4
5 public class Customer extends Person
6 {
7 private Address shipTo;
8
9 public Address getShipTo(){}
10 public void setShipTo(Address addr){}
11 }
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 4
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
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.
Declaring Methods
• Methods are written inside the body of a class.
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 }
10
11class ClassOne
12{
13 public void returnNothing()
14 {
15 //whatever the method does
16 }
17}
Object Methods
• Method must be preceded by the reference to the object
and the dot operator (“.”).
1 class MethodInvocation
2 {
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 }
11
12 class ClassOne
13 {
14 public int returnAnInt()
15 {
16 return 9;
17 }
18 }
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 class StaticExample
2 {
3 public static void main (string args[])
4 {
5 double rand = Math.random();
6 System.out.println("A random number: " + rand);
7 }
8 }
Case Study
Discussion – What static methods could you use in the order-
entry example?
Passing Arguments
• You must give values for any methods with arguments
when invoking the method.
• Arguments must be declared as a type-variable pair:
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 }
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 9, passing
the homeAddress to set the shipTo attribute.
1 package OrderEntry;
2 import OrderEntry.Person;
3 import OrderEntry.Address;
4
5 public class Customer extends Person {
6 private Address shipTo;
7
8 public void initialize() {
9 setShipTo(Address homeAddress);
10 }
11
12 public Address getShipTo(){}
13 public void setShipTo(Address addr){}
14 }
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 public abstract class Person {
2 private String firstName;
3 private String lastName;
4 private String initial;
5 private int ID;
6 private Address homeAddress;
7
8 public String getName(){return firstName;}
9 public void setFirstName(String fName){}
10 public void setLastName(String lName){}
11 public void setInitial(String init){}
12 public int getID(){return ID;}
13 public void setID(String id){}
14 public Address getAddress(){return homeAddress;}
15 public void setAddress(Address addr){}
16 }
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 method’s
signature.
Case Study
Discussion – What methods would it be useful to overload in
the order-entry system?
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.
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}
Using a Constructor
• To use a constructor to instantiate an object, use the
following syntax:
class_name reference_variable = new
constructor([arguments])
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");
Overloading Constructors
1 class Shirt
2 {
3 String type;
4
5 // Shirt() is the first constructor
6 Shirt()
7 {
8 name = "Oxford Shirt";
9 }
10
11 // Shirt(String differentType) is another
// constructor
12 Shirt(String differentType)
13 {
14 type = differentType;
15 }
16}
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.
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 5
Object Interaction
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
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.
Case Study
Discussion – In the order-entry system, which classes have an
association relationship and which have a composition
relationship?
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.
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.
Case Study
Discussion – Who has custody in the Order-Customer
relationship? Who has custody in Customer-Address?
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 6
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
<<uses>>
CSR
Assemble order
Warehouse
Legend
Actor
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
[inStock]
add()
reorder:= reorder()
[not inStock]
hold()
verify()
Legend
Legend
Classes Relationships
0..1, 1, * Multiplicities
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
[in stock]
Assign
[succeeded]
to Order
[all items
assigned
and payments
verified]
Dispatch
Order
Legend
Legend
Classes Relationships
0..1, 1, * Multiplicities
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?
Objects .....................................................................................................................................1-1
Objectives ................................................................................................................................................. 1-2
Overview of Object Orientation ............................................................................................................ 1-3
Abstraction ............................................................................................................................................... 1-4
Functional Abstraction ........................................................................................................................... 1-5
Identifying Objects .................................................................................................................................. 1-6
Case Study ................................................................................................................................................ 1-8
Identifying Object Attributes and Operations .................................................................................... 1-9
Case Study .............................................................................................................................................. 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
Case Study .............................................................................................................................................. 2-12
Abstract Classes ..................................................................................................................................... 2-13
Case Study .............................................................................................................................................. 2-14
Exercise: Grouping Objects in Classes ............................................................................................... 2-15
Check Your Progress ............................................................................................................................ 2-16
Think Beyond ........................................................................................................................................ 2-17