chapter 3: ood and writing worker classes clark savage turner, ph.d....

42
Chapter 3: OOD and Writing Chapter 3: OOD and Writing Worker Classes Worker Classes Clark Savage Turner, Ph.D. Clark Savage Turner, Ph.D. [email protected] [email protected] 805-756-6133 805-756-6133 Copyright 2003, Csturner, adapted from notes and Koffman, Wolz text. Copyright 2003, Csturner, adapted from notes and Koffman, Wolz text. Copyright © 2000 by C Scheftic. All rights reserved. Used by permission. Copyright © 2000 by C Scheftic. All rights reserved. Used by permission. These notes do rely heavily on ones originally developed These notes do rely heavily on ones originally developed by John Lewis and William Loftus to accompany by John Lewis and William Loftus to accompany Java Software Solutions © Addison-Wesley Java Software Solutions © Addison-Wesley by Ralph Morelli to accompany by Ralph Morelli to accompany Java Java Java © Prentice-Hall Java Java Java © Prentice-Hall and and by Mark Hutchenreuther for CSC-101 at Cal Poly, SLO by Mark Hutchenreuther for CSC-101 at Cal Poly, SLO © Mark Hutchenreuther © Mark Hutchenreuther

Post on 21-Dec-2015

216 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

Chapter 3: OOD and Writing Worker Chapter 3: OOD and Writing Worker Classes Classes

Clark Savage Turner, Ph.D.Clark Savage Turner, Ph.D.

[email protected]@csc.calpoly.edu

805-756-6133805-756-6133

Copyright 2003, Csturner, adapted from notes and Koffman, Wolz text.Copyright 2003, Csturner, adapted from notes and Koffman, Wolz text.

Copyright © 2000 by C Scheftic. All rights reserved. Used by permission.Copyright © 2000 by C Scheftic. All rights reserved. Used by permission.These notes do rely heavily on ones originally developedThese notes do rely heavily on ones originally developed by John Lewis and William Loftus to accompany by John Lewis and William Loftus to accompany

Java Software Solutions © Addison-WesleyJava Software Solutions © Addison-Wesley by Ralph Morelli to accompany by Ralph Morelli to accompany

Java Java Java © Prentice-HallJava Java Java © Prentice-Halland and

by Mark Hutchenreuther for CSC-101 at Cal Poly, SLO by Mark Hutchenreuther for CSC-101 at Cal Poly, SLO © Mark Hutchenreuther© Mark Hutchenreuther

Page 2: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

ObjectivesObjectives

Understand the concept of a class hierarchy.Understand the concept of a class hierarchy. Be familiar with the relationship between classes and Be familiar with the relationship between classes and

objects in a Java program.objects in a Java program. Be able to understand and write simple programs in Java.Be able to understand and write simple programs in Java. Be familiar with some of the basic principles of object-Be familiar with some of the basic principles of object-

oriented programming.oriented programming. Understand some more of the basic elements of the Java Understand some more of the basic elements of the Java

language.language.

Page 3: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

ObjectsObjects

An object has:An object has: statestate - descriptive characteristics - descriptive characteristics behaviorsbehaviors - what it can do (or can be done to it) - what it can do (or can be done to it)

Example: a coin that can be flipped Example: a coin that can be flipped so it's face shows either "heads" or "tails"so it's face shows either "heads" or "tails" One state of the coin is its current face (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.One behavior of the coin is that it can be flipped.

Note that the behavior of the coin might change its state!Note that the behavior of the coin might change its state!

Page 4: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

Another ObjectAnother Object

An object has:An object has: statestate - descriptive characteristics - descriptive characteristics behaviorsbehaviors - what it can do (or can be done to it) - what it can do (or can be done to it)

Another example: a ballAnother example: a ball The state of the ball is defined by data (the value of certain The state of the ball is defined by data (the value of certain

variables), such as:variables), such as: surface — dimpledsurface — dimpled color — whitecolor — white size — smallsize — small elasticity — firmelasticity — firm

The behavior of the ball is defined by methods (functions), such as:The behavior of the ball is defined by methods (functions), such as: Hit( )Hit( ) Roll( )Roll( ) Bounce( )Bounce( ) Throw( )Throw( )

Once again, the behavior of the ball might change its state.Once again, the behavior of the ball might change its state.

Page 5: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

Interacting ObjectsInteracting Objects

Illustration of interacting objects: the interface for Illustration of interacting objects: the interface for an automated software-ordering program.an automated software-ordering program.

Page 6: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

Interacting ObjectsInteracting Objects

The applet The applet objectobject gets data (“Joseph Smith”) gets data (“Joseph Smith”) from the from the customerNameFieldcustomerNameField objectobject and and passes it to the passes it to the orderFormorderForm objectobject..

applet

CustomerNameField

orderForm

“Joseph Smith”Give me your value!The customer’s name is

“Joseph Smith”

Page 7: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

ClassesClasses

A class is a blueprint of an object.A class is a blueprint of an object. Other comparisons: a model, pattern, or templateOther comparisons: a model, pattern, or template

Objects are created from such blueprints.Objects are created from such blueprints.

For a group of like objects, a class defines their common For a group of like objects, a class defines their common data and methods.data and methods. It merely defines them. It merely defines them. It does not create them, nor allocate memory space for their data.It does not create them, nor allocate memory space for their data.

Page 8: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

Object InstantiationObject Instantiation

An object is an instance of a class.An object is an instance of a class. When an object is declared, then memory is set aside for the data When an object is declared, then memory is set aside for the data

associated with that particular instance of the class.associated with that particular instance of the class.

Each object has its own data.Each object has its own data. Thus, each object has its own state.Thus, each object has its own state.

Each object shares its behavior Each object shares its behavior with other objects of its class.with other objects of its class. Thus, objects share the methods of the class.Thus, objects share the methods of the class.

Page 9: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

ClassificationClassification

A A hierarchy charthierarchy chart shows a classification of objects: shows a classification of objects:

Animal

Invertebrate Vertebrate

MammalFish Reptile

Horse Dog Cat

Page 10: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

The Java Class Hierarchy The Java Class Hierarchy (partial)(partial)

Object

Component

GridLayout

BorderLayout

Button

TextField

Label

TextComponentTextArea

Container

Panel

Window

java.awt

Key

Class

Abstract Class

Extends

Page 11: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

Classes Used AlreadyClasses Used Already

Name some classes we have used already.Name some classes we have used already. Some were provided by Java, including:Some were provided by Java, including:

StringString SystemSystem MathMath AppletApplet

Next we will learn to write our own classes!Next we will learn to write our own classes! Read the examples in our textbookRead the examples in our textbook In class, we will do one of our own: In class, we will do one of our own: RectangleRectangle

Page 12: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

Class DefinitionClass Definition

Five basic design questions: Five basic design questions: What What taskstasks will the object perform? will the object perform? What What informationinformation will it need to perform its tasks? will it need to perform its tasks? What What methodsmethods will it use to process its information? will it use to process its information? What information will it make What information will it make publicpublic for other objects? for other objects? What information will it What information will it hidehide from other objects? from other objects?

Page 13: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

ClassesClasses

A class contains A class contains data declarations, and data declarations, and method declarationsmethod declarations

int x, y;char ch;

Data declarationsData declarations

Method declarationsMethod declarations

Page 14: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

Data ScopeData Scope

The The scopescope of data is: of data is: the area in a program in which the area in a program in which that data can be used (referenced).that data can be used (referenced).

Data declared at the class level: Data declared at the class level: can be used by all methods in that class.can be used by all methods in that class.

Data declared within a method: Data declared within a method: can only be used in that method;can only be used in that method; is called is called local data.local data.

Page 15: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

Writing MethodsWriting Methods

A A method declarationmethod declaration specifies the code that specifies the code that will be executed when the method is invoked (or called).will be executed when the method is invoked (or called).

When a method is invoked, the flow of control When a method is invoked, the flow of control jumps to the method and jumps to the method and executes its code.executes its code.

When complete, the flow When complete, the flow returns to the place where the method was called and returns to the place where the method was called and continues.continues.

Depending on how the method was defined, the invocationDepending on how the method was defined, the invocation may return a value, ormay return a value, or may not return a value.may not return a value.

Page 16: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

myMethod();

myMethodcompute

Method Control FlowMethod Control Flow

The called method could be within the same class, in which The called method could be within the same class, in which case only the method name is neededcase only the method name is needed

Page 17: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

doIt

helpMe

helpMe();

obj.doIt();

main

Method Control FlowMethod Control Flow

The called method could be part of another class or objectThe called method could be part of another class or object

Page 18: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

The The Rectangle Class Definition Class Definition

public class Rectangle { private double length; // Instance variables private double width;

public Rectangle(double l, double w) // Constructor method { length = l; width = w; } // end Rectangle constructor

public double calculateArea() // Access method { return length * width; } // end calculateArea

} // end Rectangle class

An object’s public methods make up its interface

A public class is accessible to other classes

Instance variables are

usually private

Page 19: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

The The Rectangle Class Class

A class is a blueprint. A class is a blueprint. It describes an object's form,It describes an object's form, but but it has no content.it has no content. (cf “static”) (cf “static”)

The instance variables, length and width, have no values yet.

The class contains an object’s method definitions

A Rectangle

lengthwidth

Rectangle(l,w)calculateArea()

Page 20: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

Instance DataInstance Data

The The lengthlength andand widthwidth variables in the variables in the RectangleRectangle class are called class are called instance datainstance data because each instance (object) because each instance (object) of the of the RectangleRectangle class has its own. class has its own. A class declares the type of the data, but it does not A class declares the type of the data, but it does not

reserve any memory space for itreserve any memory space for it Every time a Every time a RectangleRectangle object is created, new object is created, new lengthlength andand widthwidth variables are created as well. variables are created as well.

The objects of a class share the method definitions, but they The objects of a class share the method definitions, but they have unique data space.have unique data space. That's the only way two separate objects can have That's the only way two separate objects can have

different states.different states.

Page 21: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

Rectangle rectangle1 = new Rectangle(30, 10);

Rectangle rectangle2 = new Rectangle(25, 20);

A Rectangle

1030length

width

Rectangle(l,w)calculateArea()

A Rectangle

2025length

width

Rectangle(l,w)calculateArea()

rectangle1 rectangle2

The objects (instances) store actual values.

Creating Creating Rectangle Instances Instances

Create, or instantiate, two instances of the Rectangle class: Create, or instantiate, two instances of the Rectangle class:

Page 22: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

Interacting with aInteracting with a Rectangle

We can use a We can use a method callmethod call to ask each object to tell us its to ask each object to tell us its area:area:

rectangle1 area 300rectangle2 area 500Printed output:

System.out.println("rectangle1 area " + rectangle1.calculateArea() );System.out.println("rectangle1 area " + rectangle1.calculateArea() );

System.out.println("rectangle2 area " + rectangle2.calculateArea() );System.out.println("rectangle2 area " + rectangle2.calculateArea() );

References to objects Method calls

Page 23: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

EncapsulationEncapsulation

You can take one of two views of an object:You can take one of two views of an object: internal:internal:

the structure of its data, the structure of its data, the algorithms used by its methodthe algorithms used by its method

external:external:the interaction of the object the interaction of the object with other objects in the programwith other objects in the program From this view, an object is an From this view, an object is an encapsulatedencapsulated entity, entity,

providing a set of specific services.providing a set of specific services. These services define the These services define the interfaceinterface to the object. to the object. Recall that an object is an Recall that an object is an abstractionabstraction, ,

hiding details from the rest of the system when that is useful to do.hiding details from the rest of the system when that is useful to do.

Page 24: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

Encapsulation Encapsulation (continued)(continued)

An object should be An object should be self-governing.self-governing.

Any changes to the object's state (its variables) Any changes to the object's state (its variables) should be accomplished by that object's methods.should be accomplished by that object's methods.

It should be difficult, if not impossible, It should be difficult, if not impossible, for an object to "reach in" and alter another object's state.for an object to "reach in" and alter another object's state.

The user, or The user, or clientclient, of an object can request its services, , of an object can request its services, but it should not have to be aware of but it should not have to be aware of how those services are accomplished.how those services are accomplished.

Page 25: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

Encapsulation Encapsulation (illustrated)(illustrated)

An encapsulated object can be thought of as a An encapsulated object can be thought of as a black box.black box. Its inner workings are hidden from the client, which can Its inner workings are hidden from the client, which can

only invoke the interface methods.only invoke the interface methods.

ClientClient Methods

Data

Page 26: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

public class Rectangle // Class Header{ // Start class body} // End class body

In General:In General: ClassModifiersopt class ClassName PedigreeoptClassModifiersopt class ClassName Pedigreeopt

public class Rectangle extends Objectpublic class Rectangle extends Object

Example:Example:

The Class HeaderThe Class Header

Page 27: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

Visibility ModifiersVisibility Modifiers

In Java, we accomplish encapsulation through the In Java, we accomplish encapsulation through the appropriate use of appropriate use of visibility modifiers.visibility modifiers.

A A modifiermodifier is a Java reserved word that specifies is a Java reserved word that specifies particular characteristics of a method or data value.particular characteristics of a method or data value.

We've used another modifier, We've used another modifier, finalfinal, to define a constant., to define a constant.

Java has three visibility modifiers: Java has three visibility modifiers: publicpublic privateprivate protectedprotected

Page 28: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

Visibility ModifiersVisibility Modifiers

Members of a class that are declared with Members of a class that are declared with public visibilitypublic visibility can be accessed from anywhere. can be accessed from anywhere.

Members of a class that are declared with Members of a class that are declared with private visibilityprivate visibility can only be accessed from inside the class. can only be accessed from inside the class.

Members declared without a visibility modifier have Members declared without a visibility modifier have default visibilitydefault visibility and can be accessed by any class in the and can be accessed by any class in the same package.same package.

When you learn about inheritance, you will then learn When you learn about inheritance, you will then learn about the use of about the use of protectedprotected visibility. visibility.

Java modifiers are discussed in detail in Appendix FJava modifiers are discussed in detail in Appendix F

In 101, we will use only the In 101, we will use only the public public and and private private modifiers.modifiers.

Page 29: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

Visibility ModifiersVisibility Modifiers

As a general rule, no object's As a general rule, no object's datadata should be declared with should be declared with public visibility.public visibility. Instance variables should usually be declared Instance variables should usually be declared privateprivate . .

This makes them inaccessible to other objects.This makes them inaccessible to other objects.Public instance variables can lead to an inconsistent state….Public instance variables can lead to an inconsistent state….

Public methods are also called Public methods are also called service methods.service methods. Methods that provide the object's services are usually declared with Methods that provide the object's services are usually declared with

publicpublic visibility so that they can be invoked by clients. visibility so that they can be invoked by clients. An object’s An object’s publicpublic methods make up its methods make up its interfaceinterface; they are used to ; they are used to

provide carefully controlled access to the private variables.provide carefully controlled access to the private variables.

A method created simply to assist a service method is called a A method created simply to assist a service method is called a support method.support method. Since a support method is not intended to be called by a client, Since a support method is not intended to be called by a client,

it should it should notnot be declared with public visibility. be declared with public visibility.

Page 30: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

Declaring Instance VariablesDeclaring Instance Variables

In GeneralIn General

FieldModifiersFieldModifiersoptopt TypeId VariableId Initializer TypeId VariableId Initializeroptopt

Fields or instance variables have Fields or instance variables have class scopeclass scope. Their . Their names can be used anywhere within the class.names can be used anywhere within the class.

Example (from an unidentified class):Example (from an unidentified class):

// Instance variables private boolean isEating = true; private boolean isSleeping = false;

Page 31: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

Problem DecompositionProblem Decomposition

Reconsider Reconsider RectangleRectangle: What : What objectsobjects do we need? do we need? The The RectangleRectangle class: class:

represents a represents a rectanglerectangle and and implements the implements the calculateAreacalculateArea command. command.

We will also need a We will also need a RectangleUserRectangleUser class class to serve as a to serve as a user interfaceuser interface. . Create one or more instances of a Create one or more instances of a RectangleRectangle (here, two) and (here, two) and Let the user interact with them Let the user interact with them

(here, assign them dimensions and print out their areas).(here, assign them dimensions and print out their areas).

Page 32: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

Class Design: Class Design: RectangleRectangle

State: State: doubledouble variables, variables, lengthlength andand widthwidth

Methods:Methods: A constructor to initialize a A constructor to initialize a RectangleRectangle A calculateArea method to determine A calculateArea method to determine

the rectangle’s the rectangle’s areaarea

Page 33: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

RectangleRectangle Class Specification Class Specification

Class Name: Class Name: RectangleRectangle Task: To represent a rectangleTask: To represent a rectangle

Information Needed (Information Needed (instance variablesinstance variables)) lengthlength: A measure of one side of the rectangle (private): A measure of one side of the rectangle (private)

widthwidth: A measure of a perpendicular side of the rectangle (private): A measure of a perpendicular side of the rectangle (private)

Manipulations Needed (Manipulations Needed (public methodspublic methods)) Rectangle()Rectangle():: A constructor method to initialize the rectangle A constructor method to initialize the rectangle

calculateArea(calculateArea()):: A method to calculate the area from the A method to calculate the area from the length and widthlength and width

Page 34: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

Designing MethodsDesigning Methods

The The publicpublic methods serve as a class’s methods serve as a class’s interfaceinterface.. If a method is intended to be used to communicate with or If a method is intended to be used to communicate with or

pass information to an object, it should be declared pass information to an object, it should be declared publicpublic . .

A class’s methods have A class’s methods have class scopeclass scope.. They can be used They can be used anywhere within the class.anywhere within the class.

Methods that do not return a value should be declared Methods that do not return a value should be declared voidvoid..

Page 35: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

Method DefinitionMethod Definition

ExampleExample

The Method HeaderThe Method HeaderMethodModifiersMethodModifiersoptopt ResultType MethodName ResultType MethodName ( ( FormalParameterList FormalParameterList ))

public static void main (String [ ] args )public static void main (String [ ] args )

public void paint (Graphics g)public void paint (Graphics g)

public void init ( )public void init ( )

public void flip ( )public void flip ( )

publicpublic double double calculateArea ( ) calculateArea ( )

public void MethodName( ) // Method Header{ // Start of method body} // End of method body

Page 36: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

Method DefinitionMethod Definition

public double calculateArea() // Access method { return length * width; } // end calculateArea

Header: This method, named calculateArea, is accessible to other objects (public), and does return a value (of type double).

Body: a block of statements that performs the calculateArea of a Rectangle.

Page 37: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

The RectangleUser Class

public class RectangleUser{ public static void main (String[ ] args) { Rectangle rectangle1 = new Rectangle(30,10); Rectangle rectangle2 = new Rectangle(25,20); System.out.println("rectangle1 area " + rectangle1.calculateArea()); System.out.println("rectangle2 area " + rectangle2.calculateArea()); } // end main()} // end RectangleUser

An application must have a main( ) method

Object Use

ObjectCreation

ClassDefinition

Page 38: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

Creating a Creating a RectangleRectangle Instance Instance

Rectangle rect1;Rectangle rect1; // Declare a reference variable// Declare a reference variable

rect1 = new Rectangle(6,4); rect1 = new Rectangle(6,4); // Create an instance// Create an instance

The reference variable, rect1, will

refer to a Rectangle, but its initial value is null.

rect1

rect1After instantiation,

rect1 refers to a

specific Rectangle object.

A Rectangle

46length

width

Rectangle(l,w)calculateArea()

Page 39: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

A Rectangle

46length

width

Create 2 Create 2 RectangleRectangle Instances Instances (cont)(cont)

Declaration and instantiation in one statement:Declaration and instantiation in one statement:

rect1

Two Rectangles, with names, rect1 & rect2, with different shapes but both will produce an area of 24.

A Rectangle

83length

width

rect2

Rectangle rect1 = new Rectangle(6, 4);

Rectangle rect2 = new Rectangle(3, 8);

Rectangle(l,w)calculateArea()

Rectangle(l,w)calculateArea()

Page 40: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

Method Call and ReturnMethod Call and Return

A A method callmethod call causes a program to transfer control to the first statement in the called method. causes a program to transfer control to the first statement in the called method.

A A return statementreturn statement returns control to the calling statement. returns control to the calling statement.

method1()

method2();

method2()

statement1;

return;

nextstatement;

Page 41: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

Define, Create/Instantiate, Use Define, Create/Instantiate, Use

Class Definition: Class Definition: Define one or more classesDefine one or more classes Rectangle, RectangleUser Rectangle, RectangleUser

Object Instantiation: Object Instantiation: Create objects as instances of the classes Create objects as instances of the classes rectangle1, rectangle2rectangle1, rectangle2

Object Use: Object Use: Use the objects to do tasks Use the objects to do tasks rectangle1.calculateArea( )rectangle1.calculateArea( )

Page 42: Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes

CPE-101

Object Oriented DesignObject Oriented Design

Encapsulation:Encapsulation:

The The Rectangle class encapsulates a state and a set of class encapsulates a state and a set of actions.actions.

Information Hiding:Information Hiding:

Rectangle state is private. state is private. Interface:Interface: Rectangle public access method, public access method,

calculateArea( ), limits the way it can be used., limits the way it can be used. Generality/Extensibility:Generality/Extensibility:

We can easily extend the functionality of We can easily extend the functionality of Rectangle . .