Transcript Ch3a slides

Chapter 3: OOD and Writing Worker
Classes
Clark Savage Turner, Ph.D.
[email protected]
805-756-6133
Copyright 2003, Csturner, adapted from notes and Koffman, Wolz text.
Copyright © 2000 by C Scheftic. All rights reserved. Used by permission.
These notes do rely heavily on ones originally developed
 by John Lewis and William Loftus to accompany 
Java Software Solutions © Addison-Wesley
 by Ralph Morelli to accompany 
Java Java Java © Prentice-Hall
and
 by Mark Hutchenreuther for CSC-101 at Cal Poly, SLO 
© Mark Hutchenreuther
CPE-101
Objectives





Understand the concept of a class hierarchy.
Be familiar with the relationship between classes and
objects in a Java program.
Be able to understand and write simple programs in Java.
Be familiar with some of the basic principles of objectoriented programming.
Understand some more of the basic elements of the Java
language.
CPE-101
Objects

An object has:



state - descriptive characteristics
behaviors - what it can do (or can be done to it)
Example: a coin that can be flipped
so it's face shows either "heads" or "tails"

One state of the coin is its current face (heads or tails).
One behavior of the coin is that it can be flipped.

Note that the behavior of the coin might change its state!

CPE-101
Another Object

An object has:



state - descriptive characteristics
behaviors - what it can do (or can be done to it)
Another example: a ball

The state of the ball is defined by data (the value of certain
variables), such as:





The behavior of the ball is defined by methods (functions), such as:


surface — dimpled
color — white
size — small
elasticity — firm
Hit( )
Roll( )
Bounce( )
Throw( )
Once again, the behavior of the ball might change its state.
CPE-101
Interacting Objects

Illustration of interacting objects: the interface for
an automated software-ordering program.
CPE-101
Interacting Objects

The applet object gets data (“Joseph Smith”)
from the customerNameField object and
passes it to the orderForm object.
applet
Give me your value!
Customer
NameField
“Joseph Smith”
The customer’s name is
“Joseph Smith”
orderForm
CPE-101
Classes

A class is a blueprint of an object.

Other comparisons: a model, pattern, or template

Objects are created from such blueprints.

For a group of like objects, a class defines their common
data and methods.


It merely defines them.
It does not create them, nor allocate memory space for their data.
CPE-101
Object Instantiation

An object is an instance of a class.


Each object has its own data.


When an object is declared, then memory is set aside for the data
associated with that particular instance of the class.
Thus, each object has its own state.
Each object shares its behavior
with other objects of its class.

Thus, objects share the methods of the class.
CPE-101
Classification

A hierarchy chart shows a classification of objects:
Animal
Invertebrate
Fish
Horse
Vertebrate
Mammal
Dog
Reptile
Cat
CPE-101
The Java Class Hierarchy (partial)
Object
Key
Extends
java.awt
Class
Button
Label
Component
Container
Abstract Class
Panel
Window
TextField
GridLayout
BorderLayout
TextComponent
TextArea
CPE-101
Classes Used Already
Name some classes we have used already.
 Some were provided by Java, including:
 String
 System
 Math
 Applet

Next we will learn to write our own classes!
 Read the examples in our textbook

In class, we will do one of our own: Rectangle
CPE-101
Class Definition

Five basic design questions:





What tasks will the object perform?
What information will it need to perform its tasks?
What methods will it use to process its information?
What information will it make public for other objects?
What information will it hide from other objects?
CPE-101
Classes

A class contains


data declarations, and
method declarations
int x, y;
char ch;
Data declarations
Method declarations
CPE-101
Data Scope

The scope of data is:



Data declared at the class level:


the area in a program in which
that data can be used (referenced).
can be used by all methods in that class.
Data declared within a method:


can only be used in that method;
is called local data.
CPE-101
Writing Methods
A method declaration specifies the code that
will be executed when the method is invoked (or called).
When


jumps to the method and
executes its code.
When


a method is invoked, the flow of control
complete, the flow
returns to the place where the method was called and
continues.
Depending


on how the method was defined, the invocation
may return a value, or
may not return a value.
CPE-101
Method Control Flow

The called method could be within the same class, in which
case only the method name is needed
compute
myMethod();
myMethod
CPE-101
Method Control Flow

The called method could be part of another class or object
main
obj.doIt();
doIt
helpMe();
helpMe
CPE-101
The Rectangle Class Definition
A public class is
accessible to other classes
public class Rectangle
{
private double length;
private double width;
// Instance variables
Instance variables are
public Rectangle(double l, double w) usually private
// Constructor method
{
length = l;
width = w;
} // end Rectangle constructor
public double calculateArea() // Access method
{
return length * width;
An object’s public
} // end calculateArea
methods make up its interface
} // end Rectangle class
The Rectangle Class

A class is a blueprint.

It describes an object's form, but
 it
has no content. (cf “static”)
A Rectangle
length
width
Rectangle(l,w)
calculateArea()
The instance variables, length
and width, have no values yet.
The class contains an
object’s method definitions
CPE-101
CPE-101
Instance Data

The length and width variables in the Rectangle
class are called instance data because each instance (object)
of the Rectangle class has its own.
 A class declares the type of the data, but it does not
reserve any memory space for it
 Every time a Rectangle object is created, new
length and width variables are created as well.

The objects of a class share the method definitions, but they
have unique data space.
 That's the only way two separate objects can have
different states.
Creating Rectangle Instances

CPE-101
Create, or instantiate, two instances of the Rectangle class:
Rectangle rectangle1 = new Rectangle(30, 10);
Rectangle rectangle2 = new Rectangle(25, 20);
rectangle1
A Rectangle
length
30
10
width
Rectangle(l,w)
calculateArea()
rectangle2
A Rectangle
length
25
20
width
Rectangle(l,w)
calculateArea()
The objects (instances)
store actual values.
CPE-101
Interacting with a Rectangle

We can use a method call to ask each object to tell us its
area:
System.out.println("rectangle1 area " + rectangle1.calculateArea() );
System.out.println("rectangle2 area " + rectangle2.calculateArea() );
References to
objects
rectangle1 area 300
Printed output: rectangle2 area 500
Method calls
CPE-101
Encapsulation
You can take one of two views of an object:
 internal:
the structure of its data,
the algorithms used by its method
 external:
the interaction of the object
with other objects in the program



From this view, an object is an encapsulated entity,
providing a set of specific services.
These services define the interface to the object.
Recall that an object is an abstraction,
hiding details from the rest of the system when that is useful to do.
CPE-101
Encapsulation (continued)
An object should be self-governing.

Any changes to the object's state (its variables)
should be accomplished by that object's methods.

It should be difficult, if not impossible,
for an object to "reach in" and alter another object's state.

The user, or client, of an object can request its services,
but it should not have to be aware of
how those services are accomplished.
CPE-101
Encapsulation (illustrated)


An encapsulated object can be thought of as a black box.
Its inner workings are hidden from the client, which can
only invoke the interface methods.
Client
Methods
Data
CPE-101
The Class Header

Example:
public class Rectangle // Class Header
{
// Start class body
}
// End class body

In General:

ClassModifiersopt class ClassName Pedigreeopt

public class Rectangle extends Object
CPE-101
Visibility Modifiers

In Java, we accomplish encapsulation through the
appropriate use of visibility modifiers.

A modifier is a Java reserved word that specifies
particular characteristics of a method or data value.

We've used another modifier, final, to define a constant.

Java has three visibility modifiers:
public
 private
 protected

CPE-101
Visibility Modifiers

Members of a class that are declared with
public visibility can be accessed from anywhere.

Members of a class that are declared with
private visibility can only be accessed from inside the class.

Members declared without a visibility modifier have
default visibility and can be accessed by any class in the
same package.

When you learn about inheritance, you will then learn
about the use of protected visibility.

Java modifiers are discussed in detail in Appendix F

In 101, we will use only the public and private modifiers.
CPE-101
Visibility Modifiers

As a general rule, no object's data should be declared with
public visibility.
 Instance variables should usually be declared private .
This makes them inaccessible to other objects.
Public instance variables can lead to an inconsistent state….

Public methods are also called service methods.



Methods that provide the object's services are usually declared with
public visibility so that they can be invoked by clients.
An object’s public methods make up its interface; they are used
to provide carefully controlled access to the private variables.
A method created simply to assist a service method is called
a support method.

Since a support method is not intended to be called by a client,
it should not be declared with public visibility.
CPE-101
Declaring Instance Variables

Example (from an unidentified class):
// Instance variables
private boolean isEating = true;
private boolean isSleeping = false;

In General
FieldModifiersopt TypeId VariableId Initializeropt

Fields or instance variables have class scope. Their
names can be used anywhere within the class.
CPE-101
Problem Decomposition
Reconsider Rectangle: What objects do we need?

The Rectangle class:
 represents a rectangle and
 implements the calculateArea command.

We will also need a RectangleUser class
to serve as a user interface.
 Create one or more instances of a Rectangle (here, two) and

Let the user interact with them
(here, assign them dimensions and print out their areas).
Class Design: Rectangle

State:
 double variables, length and width

Methods:

A constructor to initialize a Rectangle

A calculateArea method to determine
the rectangle’s area
CPE-101
Rectangle Class Specification

Class Name: Rectangle


Information Needed (instance variables)



Task: To represent a rectangle
length: A measure of one side of the rectangle (private)
width: A measure of a perpendicular side of the rectangle (private)
Manipulations Needed (public methods)


Rectangle(): A constructor method to initialize the rectangle
calculateArea(): A method to calculate the area from the
length and width
CPE-101
CPE-101
Designing Methods

The public methods serve as a class’s interface.

If a method is intended to be used to communicate with or
pass information to an object, it should be declared
public .
A class’s methods have class scope. They can be used
anywhere within the class.
Methods that do not return a value should be declared
void.


CPE-101
Method Definition

Example
public void MethodName( )
{
}

// Method Header
// Start of method body
// End of method body
The Method Header
MethodModifiersopt ResultType MethodName ( FormalParameterList )
public static
public
public
public
public
void
void
void
void
double
main
(String [ ] args )
paint
(Graphics g)
init
()
flip
()
calculateArea ( )
CPE-101
Method Definition
Header: This method,
named calculateArea, is
accessible to other objects
(public), and does return a
value (of type double).
public double calculateArea() // Access method
{
return length * width;
} // end calculateArea
Body: a block of
statements that performs
the calculateArea of a
Rectangle.
The RectangleUser Class
CPE-101
Class
Definition
An application must
public class RectangleUser
have a main( ) method
{
public static void main (String[ ] args)
{
Object
Rectangle rectangle1 = new Rectangle(30,10);
Rectangle rectangle2 = new Rectangle(25,20);
Creation
System.out.println("rectangle1 area " +
rectangle1.calculateArea());
System.out.println("rectangle2 area " +
rectangle2.calculateArea());
Object
} // end main()
Use
} // end RectangleUser
Creating a Rectangle Instance
Rectangle rect1;
rect1
CPE-101
// Declare a reference variable
The reference variable, rect1, will
refer to a Rectangle, but its
initial value is null.
rect1 = new Rectangle(6,4); // Create an instance
A Rectangle
rect1
length
width
6
4
Rectangle(l,w)
calculateArea()
After instantiation,
rect1 refers to a
specific Rectangle
object.
Create 2 Rectangle Instances (cont)

CPE-101
Declaration and instantiation in one statement:
Rectangle rect1 = new Rectangle(6, 4);
Rectangle rect2 = new Rectangle(3, 8);
A Rectangle
rect1
length
width
6
4
Rectangle(l,w)
calculateArea()
rect2
A Rectangle
length
width
3
8
Rectangle(l,w)
calculateArea()
Two Rectangles, with
names, rect1 & rect2,
with different shapes
but both will produce
an area of 24.
CPE-101
Method Call and Return

A method call causes a program to transfer control to the
first statement in the called method.

A return statement returns control to the calling statement.
method1()
method2()
statement1;
method2();
nextstatement;
return;
CPE-101
Define, Create/Instantiate, Use



Class Definition:
Define one or more classes
 Rectangle, RectangleUser
Object Instantiation:
Create objects as instances of the classes
 rectangle1, rectangle2
Object Use:
Use the objects to do tasks
 rectangle1.calculateArea( )
CPE-101
Object Oriented Design



Encapsulation:
The Rectangle class encapsulates a state and a set of
actions.
Information Hiding:
Rectangle state is private.
Interface:
Rectangle public access method,
calculateArea( ), limits the way it can be used.

Generality/Extensibility:
We can easily extend the functionality of Rectangle .