Top Banner
Class References, Object Containment and Methods 1
99

Section3 containment and methods

Apr 16, 2017

Download

Education

Dương Tùng
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Section3 containment and methods

Class References, Object

Containment and Methods

1

Page 2: Section3 containment and methods

Runner's training log

• Sometimes information not only consist of several pieces of information, but one of its constituents consists of several pieces, too.

• Take a look at this problem:– Develop a program that manages a runner's training log.

Every day the runner enters one entry concerning the day's run. Each entry includes the day's date, the distanceof the day's run, the duration of the run, and a commentdescribing the runner's post-run feeling.

2

Page 3: Section3 containment and methods

Log Entry examples

• A log entry consists of four pieces of information: a date, a distance, a duration, and a comment. – To represent the last three, we can use primitive types;

double (in miles), int (in minutes), and String– Representation for dates consists of three pieces: day,

month, year

• Examples: – on June 5, 2003: 5.3 miles in 27 minutes, feeling good; – on June 6, 2003: 2.8 miles in 24 minutes, feeling tired – on June 23, 2003: 26.2 miles in 150 minutes, feeling

exhausted;

3

Page 4: Section3 containment and methods

Class Diagram

4

Entry- Date date- double distance- int duration- String comment

Date- int day- int month- int year

Page 5: Section3 containment and methods

Define class and constructor

5

public class Entry {private Date date;private double distance;private int duration;private String comment;public Entry(Date date, double distance, int duration,

String comment) {this.date = date;this.distance = distance;this.duration = duration;this.comment = comment;

}}

public class Date {private int day;private int month;private int year;public Date(int day, int month,

int year) {this.day = day;this.month = month;this.year = year;

}}

contain

Page 6: Section3 containment and methods

Test constructor

6

import junit.framework.*;public class EntryTest extends TestCase {

public void testDateContructor() {new Date(5, 6, 2004);Date date1 = new Date(6, 6, 2004);Date date2 = new Date(23, 6, 2004);

}

public void testEntryContructor() {new Entry(new Date(5, 6, 2004), 5.3, 27, "good");

Date date1 = new Date(6, 6, 2004);new Entry(date1, 2.8, 24, "tired");

Date date2 = new Date(23, 6, 2004);new Entry(date2, 26.2, 159, "exhausted");

}}

Page 7: Section3 containment and methods

Methods for containment

7

Page 8: Section3 containment and methods

Add methods to the Entry

8

??? nnn(???)

Entry- Date date- double distance- int duration- String comment

Date- int day- int month- int year

??? kkk(???)

Page 9: Section3 containment and methods

Java template for Entry

9

public class Entry {private Date date;private double distance;private int duration;private String comment;public Entry(Date date, double distance, int duration,

String comment) {this.date = date;this.distance = distance;this.duration = duration;this.comment = comment;

}

public ??? nnn(???) {...this.date.kkk(???)...

...this.distance...this.duration...this.comment...

}}

Page 10: Section3 containment and methods

Java template for Entry

10

public class Date {private int day;private int month;private int year;public Date(int day, int month,

int year) {this.day = day;this.month = month;this.year = year;

}

public ??? kkk(???) {...this.day...this.month...this.year...

}}

Page 11: Section3 containment and methods

Computes the pace for a daily entry

• For each entry, the program should compute how fast the runner ran in minutes per mile. ... Develop a method that computes the pace for a daily entry.

??? pace(???)

Entry- Date date- double distance- int duration- String comment

Date- int day- int month- int year

11

Page 12: Section3 containment and methods

Design pace() method

• Purpose and contract (method signature)// computes the pace for a daily entrypublic double pace() {

}

• Examples– new Entry(new Date(5, 6, 2004), 5.3, 27, "good").pace() should produce 5.094

– new Entry(new Date(6, 6, 2004), 2.8, 24, "tired").pace() should produce 8.571

– new Entry(new Date(23, 6, 2004), 26.2, 159, "exhausted").pace() should produce 6.069

12

Page 13: Section3 containment and methods

Design pace() method (con't)

13

public double pace() {return this.duration / this.distance;

}

// computes the pace for a daily entrypublic double pace() {

...this.date...

...this.duration...

...this.distance...

...this.comment...}

Template

Implement

Page 14: Section3 containment and methods

Design pace() method (con't)

• Unit testing

14

public void testPace() {Entry entry1 = new Entry(new Date(5, 6, 2004), 5.3, 27, "good");assertEquals(entry1.pace(), 5.094, 0.001);

Entry entry2 = new Entry(new Date(6, 6, 2004), 2.8, 24, "tired");assertEquals(entry2.pace(), 8.571, 0.001);

Entry entry3 = new Entry(new Date(23, 6, 2004), 26.2, 159, "exhausted");assertEquals(entry3.pace(), 6.069, 0.001);

}

Page 15: Section3 containment and methods

Compare Date: early than

• A runner's log refers to Dates and a natural question concerning comparing dates is when one occurs earlier than another one. Develop a method that determines whether one date occurs earlier than another date.

• Hint: – The first possibility is that the first date is in the year preceding

the other.– Next, if the years are the same, the month in the first date is

before the month in the second date.– Finally, if both the year and the month values are the same, the

date in the first date is before the day in the second date.

15

Page 16: Section3 containment and methods

Delegation

• Q: Which class (Entry or Date) should we put ealierThan() method in ?

• A: The ealierThan() method deals with properties of the Date so that we delegate this computational task to the corresponding methods in Date class

16

??? ealierThan(???)

Entry

- Date date- double distance- int duration- String comment

Date

- int day- int month- int year

Page 17: Section3 containment and methods

Design earlierThan() method

• Purpose and contract (method signature)// is this date early than the other datepublic boolean earlierThan(Date that)

• Examples– new Date(30, 6, 2003).earlierThan(new Date(1, 1, 2004)) should produce true

– new Date(1, 1, 2004).earlierThan(new Date(1, 12, 2003)) should produce false

– new Date(15, 12, 2004).earlierThan(new Date(31, 12, 2004)) should produce true

17

Page 18: Section3 containment and methods

Design earlyThan() method (con't)

18

public boolean earlierThan(Date that) {if (this.year < that.year) return true;if (this.year > that.year) return false;if (this.month < that.month) return true;if (this.month > that.month) return false;if (this.day < that.day) return true;return false;

}

// is this date early than the other date public double earlyThan(Date that) {

...this.day...this.month...this.year...

...that.day...that.month...that.year...}

Template

Implement

Page 19: Section3 containment and methods

Unit Testing

19

pubblic class EntryTest extends TestCase {...public void testEarlierThan() {

Date date1 = new Date(30, 6, 2003);Date date2 = new Date(1, 1, 2004);Date date3 = new Date(1, 12, 2004);Date date4 = new Date(15, 12, 2004);Date date5 = new Date(31, 12, 2004);

assertTrue(date1.earlierThan(date2));assertTrue(date2.earlierThan(date3));assertTrue(date3.earlierThan(date4));assertTrue(date4.earlierThan(date5));

assertFalse(date1.earlierThan(date1));assertFalse(date5.earlierThan(date4));assertFalse(date4.earlierThan(date3));assertFalse(date3.earlierThan(date2));assertFalse(date2.earlierThan(date1));

}}

Page 20: Section3 containment and methods

Restaurant example

• Develop a program that helps a visitor navigate Manhattan's restaurant scene. The program must be able to provide four pieces of information for each restaurant: its name, the kind of food it serves, its price range, and the closest intersection(street and avenue).

• Examples: – La Crepe, a French restaurant, on 7th Ave and 65th Street,

moderate; – Bremen Haus, a German restaurant on 2nd Ave and 86th Street,

moderate; – Moon Palace, a Chinese restaurant on 10th Ave and 113th Street,

inexpensive;

20

avenue

Page 21: Section3 containment and methods

Class Diagram

21

Restaurant- String name- String food- String priceRange- Intersection intersection

Intersection- int avenue- int street

Page 22: Section3 containment and methods

Problem Statement

• Develop a method to help visitors to find out whether two restaurants are close to each other

• Two restaurants are "close'' to each other if they are at most one avenue and at most one street away from each other

• Notice: This is an interesting example!

• Q: Add this method to the class diagram

22

Page 23: Section3 containment and methods

23

B(2, 2)

C(3, 2)

D(4, 2)

F(2, 3)

G(3, 3)

H(4, 3)

Avenue 2 3 4

Street

4

3

2

X(Street, Avenue)

The considered Intersection

G “closes” B, C, D, F, H, L, M, N

L(2, 4)

M(3, 4)

(2, 5)

P(3, 5)

(2, 1)

A(3, 1)

4, 1)

1 5

(5, 2) K(5, 3)5 (5, 1)

(1, 2) E(1, 3)1 (1, 4) (1, 5)(1, 1)

N(4, 4)

Intersections “close” to the considered

Intersection

Intersections not “close” to the considered

Intersection

K(5, 4) K(5, 5)

Page 24: Section3 containment and methods

Delegation

Q: Which class (Restaurant or Intersection) should we put closeTo() method in ? A: Put closeTo() in both classes.

– The closeTo() method deals with properties of the Intersection so that we delegate this computational task to the corresponding methods in Intersection class

24

Restaurant- String name- String food- String priceRange- Intersection intersection

+ boolean closeTo(Restaurant that)

Intersection- int avenue- int street

+ boolean closeTo(Intersection that)

Q: Create examples for the method closeTo() in the Intersection class

Page 25: Section3 containment and methods

Examples

25

Intersection i1 = new Intersection(3, 3);

Intersection i2 = new Intersection(3, 2);

i1.closeTo(i2); // should produce true

i1.closeTo(new Intersection(3, 5)); // should produce false

i2.closeTo(new Intersection(3, 5)); // should produce false

Restaurant r1 = new Restaurant("La Crepe", "French",

"moderate", new Intersection(3, 3));

Restaurant r2 = new Restaurant("Das Bier", "German",

"cheap", new Intersection(3, 2));

Restaurant r3 = new Restaurant("Sun", "Chinese",

"cheap", new Intersection(3, 5));

r1.closeTo(r2); // should produce true

r1.closeTo(r3); // should produce false

r2.closeTo(r3); // should produce false

Page 26: Section3 containment and methods

closeTo template in Intersection class

26

public class Intersection {private int avenue;private int street;public Intersection(int avenue, int street) {

this.avenue = avenue;this.street = street;

}

// is this intersection close to anotherpublic boolean closeTo(Intersection that) {

...this.avenue...

...this.street...

...that.avenue...

...that.street...}

}

Page 27: Section3 containment and methods

closeTo template in Restaurant class

27

public class Restaurant {private String name;private String food;private String priceRange;private Intersection intersection;...

// is this restaurant close to anotherpublic boolean closeTo(Restaurant that) {

...this.name...

...this.food...

...this.priceRange...

...this.intersection.closeTo(...)...

...that.name...

...that.food...

...that.priceRange...

...that.intersection.closeTo(...)...}

}

Page 28: Section3 containment and methods

Method Implementation

28

public class Intersection {...

public boolean closeTo(Intersection that) {return ((Math.abs(this.avenue - that.avenue) <=1) &&

(Math.abs(this.street - that.street) <= 1));}

}

public class Restaurant {...public boolean closeTo (Restaurant that) {

return this.intersection.closeTo(that.intersection);}

}

Page 29: Section3 containment and methods

Unit Testing

29

public void testCloseTo() {

Restaurant r1 = new Restaurant("La Crepe", "French", "moderate",

new Intersection(3, 3));

Restaurant r2 = new Restaurant("Das Bier", "German", "cheap",

new Intersection(3, 2));

Restaurant r3 = new Restaurant("Sun", "Chinese", "cheap",

new Intersection(3, 5));

assertTrue(r1.closeTo(r2));

assertFalse(r1.closeTo(r3));

assertFalse(r2.closeTo(r3));

}

Page 30: Section3 containment and methods

Relax &

…Do Exercises …

30

Page 31: Section3 containment and methods

Rectangle example

• The rectangles have width, height and are located on the Cartesian plane of a computer canvas, which has its origin in the northwest corner.

31

Rectangle- CartPt nwCorner- int width- int height

CartPt- int x- int y

Page 32: Section3 containment and methods

Problem Statement

...Design a method that computes the distance of a Rectangle to the origin of the canvas.• Considering that a Rectangle has many points, the

meaning of this problem is clearly to determine the shortest distance of the Rectangle to the origin.

• This, in turn, means computing the distance between its northwest corner and the origin

32

X

y

Y

O

Rectangle

x

northwest corner

Page 33: Section3 containment and methods

Problem Analysis

We need two methods:

1. Measuring the distance of a Rectangle to the origin

2. Measuring the distance of a CartPt to the origin

Q: Add these two methods to the class diagram

33

Page 34: Section3 containment and methods

Delegation

• Q: Which class (Rectangle or CartPt) should we put distanceToO() method in ?

• A: Put distanceToO() in both classes.– The distanceToO() method deals with properties of the CartPt so that we delegate this computational task to the corresponding methods in CartPt class

34

CartPt- int x- int y

+ double distanceToO()

Rectangle- CartPt nwCorner- int width- int height

+ double distanceToO()

Page 35: Section3 containment and methods

distanceToO – Examples

35

CartPt p = new CartPt(3, 4);CartPt q = new CartPt(5, 12);

Rectangle r = new Rectangle(p, 5, 17);Rectangle s = new Rectangle(q, 10, 10);

p.distanceToO() // should produce 5q.distanceToO() // should produce 13r.distanceToO() // should produce 5s.distanceToO() // should produce 13

Page 36: Section3 containment and methods

distanceToO – Purpose and signature

36

public class Rectangle { private CartPt nwCorner; private int width; private int height; public Rectangle(CartPt nwCorner,

int width, int height) { ... }

// to compute the distance of this Rectangle to the origin public double distanceToO() { ... }

}

public class CartPt {private int x;private int y;public CartPt(int x, int y) { ... }

// to compute the distance of this point to the originpublic double distanceToO() { ... }

}

Page 37: Section3 containment and methods

distanceToO – Template

37

public class CartPt {...

// to compute the distance of this point to the originpublic double distanceToO() {

...this.x...

...this.y...}

}

public class Rectangle {...

// to compute the distance of this Rectangle to the originpublic double distanceToO() {

...this.nwCorner.distanceToO()...

...this.width...

...this.height...}

}

Page 38: Section3 containment and methods

distanceToO Method Implementation

38

public class CartPt {private int x;private int y;

public CartPt(int x, int y) {this.x = x;this.y = y;

}

// to compute the distance of this CartPt to the originpublic double distanceToO() {

return Math.sqrt(this.x * this.x + this.y * this.y);}

}

Tips: Math.sqrt is the name of the method that computes the square root of its argument as a double.

Page 39: Section3 containment and methods

distanceToO Method Implementation

39

public class Rectangle {

private CartPt nwCorner;

private int width;

private int height;

public Rectangle(CartPt nwCorner,

int width, int height) {

this.nwCorner = nwCorner;

this.width = width;

this.height = height;

}

// to compute the distance of this Rectangle to the origin

public double distanceToO() {

return this.nwCorner.distanceToO();

}

}

Page 40: Section3 containment and methods

distanceToO – Unit Testing

40

public void testDistanceToO() {

CartPt p = new CartPt(3, 4);

Rectangle r = new Rectangle(p, 5, 17);

assertEquals(r.distanceToO(), 5, 0.001);

p = new CartPt(5, 12);

r = new Rectangle(p, 10, 10);

assertEquals(r.distanceToO(), 13, 0.001);

}

Page 41: Section3 containment and methods

Problem Extension Statement

• Compute the distance between the rectangle’s center and the origin

41

y

X

Y

0

x

center of retangle

width

height

Page 42: Section3 containment and methods

Solution 1

42

public class Rectangle {

private CartPt nwCorner;

private int width;

private int height;

public Rectangle(CartPt nwCorner, int width, int height) {

this.nwCorner = nwCorner;

this.width = width;

this.height = height;

}

public double distanceToO() {

return this.nwCorner.distanceToO();

}

public double distanceFromCenterToO() {

int a = this.nwCorner.getX() + this.width/2;

int b = this.nwCorner.getY() + this.height/2;

return Math.sqrt(a*a + b*b);

}

}

Q: Is it right?A: right, but the delegation is not applied.

Page 43: Section3 containment and methods

public class CartPt {private int x;private int y;public CartPt(int x, int y) {

this.x = x;this.y = y;

}

public double distanceToO() {return Math.sqrt(this.x * this.x + this.y * this.y);

}

public int getX() {return this.x;

}

public int getY() {return this.y;

}}

Solution 1 (cont)

43

getter

Page 44: Section3 containment and methods

Solution 2

44

public class Rectangle {private CartPt nwCorner;private int width;private int height;...public double distanceToO() {

return this.nwCorner.distanceToO();}

public double distanceFromCenterToO() {return this.center().distanceToO();

}

private CartPt center() {int a = this.nwCorner.getX() + this.width / 2;int b = this.nwCorner.getY() + this.height / 2;return new CartPt(a, b);

}}

Q: How to find the value of the center?

Page 45: Section3 containment and methods

Class diagram

45

Rectangle

- CatesianPoint northWestConner- int height- int width

+ double distanceToO()+ double distanceFromCenterToO()+ CartPt center()

CartPt- int x- int y

+ double distanceToO()+ int getX()+ int getY()

Page 46: Section3 containment and methods

Circle example

• The circle are located on the Cartesian plane of a computer canvas, which has its center and radius.

• Compute the distance form circle to the origin

• Computing the perimeter of a circle

• Computing the area of a circle.

• Computes the area of a ring, that is, this disk with a hole in the center

46

Page 47: Section3 containment and methods

Distance form circle to the origin

47

y

X

Y

0

x

center of circle

Circle- CartPt center- int radius

+ double distanceToO()

CartPt- int x- int y

+ double distanceToO()+ int getX()+ int getY()

Page 48: Section3 containment and methods

distanceToO template

48

public class Circle {private CartPt center;private int radius;

public Circle(CartPt center, int radius) {this.center = center;this.radius = radius;

}

public double area() {return Math.PI*this.radius*this.radius;

}

// to compute the distance of this Circle to the originpublic doublle distanceToO() {

...this.center.distanceToO()...this.center.getX()...

...this.center.getY()...

...this.radius...}

Page 49: Section3 containment and methods

distanceToO body

49

public class Circle {private CartPt center;private int radius;

public Circle(CartPt center, int radius) {this.center = center;this.radius = radius;

}

// to compute the distance of this Circle to the originpublic double distanceToO() {

return this.center.distanceToO();}

}

Page 50: Section3 containment and methods

distanceToO test

50

public void testDistanceTo0() {

Circle c1 = new Circle(new CartPt(3, 4), 5);

Circle c2 = new Circle(new CartPt(5, 12), 10);

Circle c3 = new Circle(new CartPt(6, 8), 20);

assertEquals(c1.distanceToO(), 5.0, 0.001);

assertEquals(c2.distanceToO(), 13.0, 0.001);

assertEquals(c3.distanceToO(), 10.0, 0.001);

}

Page 51: Section3 containment and methods

perimeter template

51

public class Circle {private CartPt center;private int radius;

public Circle(CartPt center, int radius) {this.center = center;this.radius = radius;

}

// Compute the perimeter of the circlepublic double perimeter () {

...this.distanceToO()...

...this.center.distanceToO()

...this.center.getX()...this.center.getY()...

...this.radius...}

}

Page 52: Section3 containment and methods

perimeter body

52

public class Circle {

private CartPt center;

private int radius;

public Circle(CartPt center, int radius) {

this.center = center;

this.radius = radius;

}

//Compute the perimeter of the circle

public double perimeter() {

return 2* Math.PI * this.radius;

}

}

Page 53: Section3 containment and methods

perimeter Test

53

public void testPerimeter() {

Circle c1 = new Circle(new CartPt(3, 4), 5);

Circle c2 = new Circle(new CartPt(5, 12), 10);

Circle c3 = new Circle(new CartPt(6, 8), 20);

assertEquals(c1.perimeter(), 31.42, 0.001);

assertEquals(c2.perimeter(), 62.83, 0.001);

assertEquals(c3.perimeter(), 125.66, 0.001);

}

Page 54: Section3 containment and methods

area template

54

public class Circle {private CartPt center;private int radius;

public Circle(CartPt center, int radius) {this.center = center;this.radius = radius;

}...

//Compute the area of the circlepublic double area () {

...this.distanceToO()...

...this.perimeter()...

...this.center.distanceToO()...this.center.getX()...

...this.center.getY()...

...this.radius...}

}

Page 55: Section3 containment and methods

area body

55

public class Circle {

private CartPt center;

private int radius;

public Circle(CartPt center, int radius) {

this.center = center;

this.radius = radius;

}

//Compute the perimeter of the circle

public double area() {

return Math.PI * this.radius * this.radius;

}

}

Page 56: Section3 containment and methods

area Test

56

public void testArea() {

Circle c1 = new Circle(new CartPt(3, 4), 5);

Circle c2 = new Circle(new CartPt(5, 12), 10);

Circle c3 = new Circle(new CartPt(6, 8), 20);

assertEquals(c1.area(), 78.54, 0.001);

assertEquals(c2.area(), 314.16, 0.001);

assertEquals(c3.area(), 1256.64, 0.001);

}

Page 57: Section3 containment and methods

Area of ring

57

X

y

Y

0

x

Area of ring

Page 58: Section3 containment and methods

area template

58

public class Circle {private CartPt center;private int radius;public Circle(CartPt center, int radius) {

this.center = center;this.radius = radius;

}// Compute the area of the circle

public double area() {

return Math.PI * this.radius * this.radius;

}

// Compute the area of the ringpublic double area(Circle that) {

...this.center...this.radius...

...this.distanceToO()...this.perimeter()...this.area()...

...that.center...that.radius...

...that.distanceToO()...that.perimeter()...that.area()...}

}

Page 59: Section3 containment and methods

area body

59

public class Circle {

private CartPt center;

private int radius;

public Circle(CartPt center, int radius) {

this.center = center;

this.radius = radius;

}

// Compute the area of the circle

public double area() {

return Math.PI * this.radius * this.radius;

}

// Compute the area of the ring

public double area(Circle that) {

return Math.abs(this.area() - that.area());

}

}

Page 60: Section3 containment and methods

area Test

60

public void testArea() {

Circle c1 = new Circle(new CartPt(3, 4), 5);

Circle c2 = new Circle(new CartPt(5, 12), 10);

Circle c3 = new Circle(new CartPt(6, 8), 20);

assertEquals(c1.area(), 78.54, 0.01);

assertEquals(c2.area(), 314.16, 0.01);

assertEquals(c3.area(), 1256.64, 0.01);

assertEquals(c2.area(c1), 235.62, 0.01);

assertEquals(c3.area(c1), 1178.1, 0.01);

assertEquals(c3.area(c2), 942.48, 0.01);

}

Page 61: Section3 containment and methods

Overloading method

• Q: what happen with the same name area() and area(Circle) method?

• A:– Method area() and area(Cirlce ) in class Cirlce have

the same name but different parameter is called overloading.

– When we invoke overloading methods, the method with appropriate argument will do

61

Page 62: Section3 containment and methods

Class diagram

62

1

Circle- CartPt center- int radius

+ double distanceToO()+ double perimeter()+ double area()+ double area(Circle that)

CartPt- int x- int y

+ double distanceToO()+ int getX()+ int getY()

Page 63: Section3 containment and methods

Cylinder example

• The information of the cylinder includes base disk and its height. Compute the volume of the cylinder

• Compute the surface area of the cylinder

63

Cylinder- Circle baseDisk- int height

+ double volume()+ double surface()

Circle- CartPt center- int radius

+ double distanceTo0()+ double perimeter()+ double area()+ double area(Circle that)

CartPt- int x- int y

+ double distanceTo0()+ int getX()+ int getY()

Page 64: Section3 containment and methods

volume method template

64

public class Cylinder {private Circle baseDisk;private int height;

public Cylinder(Circle baseDisk, int height) {this.baseDisk = baseDisk;this.height = height;

}

// Compute the volume of the cylinderpublic double volume() {

...this.baseDisk.distanceToO()

...this.baseDisk.perimeter()...this.baseDisk.area()...

...this.height...}

}

Page 65: Section3 containment and methods

volume method body

65

public class Cylinder {private Circle baseDisk;private int height;

public Cylinder(Circle baseDisk, int height) {this.baseDisk = baseDisk;this.height = height;

}

// Compute the volume of the cylinderpublic double volume() {

return this.baseDisk.area() * this.height;}

}

Page 66: Section3 containment and methods

volume method test

66

public void testVolume(){Circle c1 = new Circle(new CartPt(3,4), 5);Circle c2 = new Circle(new CartPt(5,12), 10);Circle c3 = new Circle(new CartPt(6,8), 20);

Cylinder cy1 = new Cylinder(c1, 10);Cylinder cy2 = new Cylinder(c2, 30);Cylinder cy3 = new Cylinder(c3, 40);

assertEquals(cy1.volume(), 785.4, 0.001);assertEquals(cy2.volume(), 9424.77, 0.001);assertEquals(cy3.volume(), 50265.48, 0.001);

}

Page 67: Section3 containment and methods

surface method template

67

public class Cylinder {private Circle baseDisk;private int height;public Cylinder(Circle baseDisk, int height) {

this.baseDisk = baseDisk;this.height = height;

}

// Compute the surface of the cylinderpublic double surface(){

...this.baseDisk.distanceToO()

...this.baseDisk.perimeter()...this.baseDisk.area()...

...this.height...}

}

Page 68: Section3 containment and methods

surface method body

68

public class Cylinder {private Circle baseDisk;private int height;public Cylinder(Circle baseDisk, int height) {

this.baseDisk = baseDisk;this.height = height;

}

// Compute the volume of the cylinderpublic double volume() {

return this.baseDisk.area() * this.height;}

// Compute the surface of the cylinderpublic double surface() {

return this.baseDisk.perimeter() * this.height;}

}

Page 69: Section3 containment and methods

surface method test

69

public void testSurface() {Circle c1 = new Circle(new CartPt(3, 4), 5);Circle c2 = new Circle(new CartPt(5, 12), 10);Circle c3 = new Circle(new CartPt(6, 8), 20);

Cylinder cy1 = new Cylinder(c1, 10);Cylinder cy2 = new Cylinder(c2, 30);Cylinder cy3 = new Cylinder(c3, 40);

assertEquals(cy1.surface(), 314.16, 0.001);assertEquals(cy2.surface(), 1884.95, 0.001);assertEquals(cy3.surface(), 5026.54, 0.01);

}

Page 70: Section3 containment and methods

Class diagram

70

Cylinder- Circle baseDisk- int height

+ double volume()+ double surface()

Circle- CartPt center- int radius

+ double distanceTo0()+ double perimeter()+ double area()+ double area(Circle that)

CartPt- int x- int y

+ double distanceTo0()+ int getX()+ int getY()

Page 71: Section3 containment and methods

Exercises

71

• Part III: Exercise 3.1.3 (HTDCH)

• Exercise 4.1.1 to 4.1.2 (HTDCH)

Page 72: Section3 containment and methods

Exercise 3.1.3 (HTDCH)

Develop a "real estate assistant'' program. The "assistant'' helps the real estate agent locate houses of interest for clients. The information about a house includes its kind, the number of rooms, the asking price, and its address. An address consists of a house number, a street name, and a city.• Represent the following examples using your classes:

– Ranch, 7 rooms, $375,000, 23 Maple Street, Brookline– Colonial, 9 rooms, $450,000, 5 Joye Road, Newton– Cape, 6 rooms, $235,000, 83 Winslow Road, Waltham

• Develop the following methods for the class House: – hasMoreRooms, which determines whether one house has more

rooms than some other house;– inThisCity, which checks whether the advertised house is in

some given city (assume we give the method a city name);– sameCity, which determines whether one house is in the same city

as some other house.

72

Solution

Page 73: Section3 containment and methods

• Ranch– A ranch is a large farm used for raising animals, especially

cattle, horses or sheep.

• Colonial– A colonial building or piece of furniture was built or made in

a style that was popular in American in the 17th and 18th

centuries.

• Cape– A cape is a large piece of land that sticks out into the sea

from the coast.

73

Back

Page 74: Section3 containment and methods

Exercise 4.1.1

. . . Develop a program that assists bookstore employees. For each book, the program should track the book’s title, its price, its year of publication, and the author. A author has a name and birth year.• Develop the following methods for this class:

– currentBook that checks whether the book was published in 2004 or 2003;

– currentAuthor that determines whether a book was written by a current author (born after 1940);

– thisAuthor that determines whether a book was written by the specified author;

– sameAuthor that determines whether one book was written by the same author as some other book;

– sameGeneration that determines whether two books were written by two authors born less than 10 year apart.

74Solution

Page 75: Section3 containment and methods

Exercise 4.1.2

• Exercise 3.1.2 provides the data definition for a weather recording program.

• Develop the following methods: – withinRange, which determines whether today's high and

low were within the normal range; – rainyDay, which determines whether the precipitation is

higher than some given value; – recordDay, which determines whether the temperature

broke either the high or the low record.

75

Solution

WeatherRecord

-Date d-TemperatureRange today-TemperatureRange normal-TemperatureRange record-double precipitation

Date

-int day-int month-int year

TemperatureRange

-int low-int high

Page 76: Section3 containment and methods

Extended Exercises(Lab hours)

Develop a program that can railway travelers with the arrangement of train trips.• The available information about a specific train includes

its schedule, its route, and whether it is local.• The route information consists of the origin and the

destination station.• A schedule specifies the departure and the arrival

(clock) times when the train leaves and when it arrives. • ClockTime consists of the hour (of the day) and the

minutes (of the hour). • The customer want to know:

– Does his destination station match the destination of the train trip?

– What time does the train start ?– How long does the train trip take?

76

Page 77: Section3 containment and methods

Relax &

…Do Exercises …

77

Page 78: Section3 containment and methods

Solution 3.1.3

78

House

-String kind-int nRooms-Address address-int price

Address

-String houseNumber-String street-String city

Page 79: Section3 containment and methods

Solution 3.1.3: House class

79

public class House {private String kind;private int nRooms;private Address address;private int price;

public House(String kind, int nRooms, Address address, int price) {

this.kind = kind;this.nRooms = nRooms;this.address = address;this.price = price;

}...

}

Page 80: Section3 containment and methods

Solution 3.1.3: Address class

public class Address {private String houseNumber;private String street;private String city;

public Address(String houseNumber, String street, String city) {

this.houseNumber = houseNumber;this.street = street;this.city = city;

}...

}

80

Page 81: Section3 containment and methods

hasMoreRooms() and Unit testing

• Method implementation

81

public boolean hasMoreRooms(House that) {return this.nRooms > that.nRooms;

}

public void testHasMoreRooms() {House house1 = new House("Ranch", 7,

new Address("23", "Mapple Street", "Brooklyn"), 375000);House house2 = new House("Colonial", 9,

new Address("5", "Jove Road", "Newton"), 450000);House house3 = new House("Cape", 6,

new Address("83", "Winslow Road", "Waltham"), 235000);assertFalse(house1.hasMoreRooms(house2));assertTrue(house2.hasMoreRooms(house3));

}

• Unit Test

Page 82: Section3 containment and methods

inThisCity()

82

// class Addresspublic boolean inThisCity(String thatCity) {

return this.city.equals(thatCity);}

// class Housepublic boolean inThisCity(String city) {

return this.address.inThisCity(city);}

Page 83: Section3 containment and methods

inThisCity() Unit testing

83

public void testThisCity() {House house1 = new House("Ranch", 7,

new Address("23", "Mapple Street", "Brooklyn"), 375000);House house2 = new House("Colonial", 9,

new Address("5", "Jove Road", "Newton"), 450000);House house3 = new House("Cape", 6,

new Address("83", "Winslow Road", "Waltham"), 235000);assertTrue(house1.inThisCity("Brooklyn"));assertFalse(house1.inThisCity("Newton"));

}

Page 84: Section3 containment and methods

sameCity()

84

// class Housepublic boolean sameCity(House that) {

return this.address.sameCity(that.address);}

// class Addresspublic boolean sameCity(Address that) {

return this.city.equals(that.city);}

Page 85: Section3 containment and methods

sameCity() Unit Test

85

public void testSameCity() {House house1 = new House("Ranch", 7,

new Address("23", "Mapple Street", "Brooklyn"), 375000);House house2 = new House("Colonial", 9,

new Address("5", "Jove Road", "Newton"), 450000);House house3 = new House("Cape", 6,

new Address("83", "Winslow Road", "Waltham"), 235000);assertTrue(house1.sameCity(house1));assertFalse(house1.sameCity(house2));

}

Page 86: Section3 containment and methods

Solution 4.1.1

86

Book

-String title-double price-int publishYear-Author author

Author

-String name-int birthYear

Page 87: Section3 containment and methods

currentBook()

• Method implementation

87

public boolean currentBook() {return (this.publishYear == 2004) ||

(this.publishYear == 2003);}

Page 88: Section3 containment and methods

currentBook() Unit testing

88

public void testCurrentBook() {

Author felleisen =

new Author("Matthias Felleisen", 1960);

Book htdch = new Book(felleisen, "How to Design Class Hierarchies", 0.0, 2004);

assertTrue(htdch.currentBook());

Author friedman = new Author("Daniel P. Friedman", 1939);

Book aljafp = new Book(friedman,

"A Little Java, A Few Pattern", 25.9, 1998);

assertFalse(aljafp.currentBook());

}

Page 89: Section3 containment and methods

currentAuthor()

• Method implementation

89

// in class Bookpublic boolean currentAuthor() {

return this.author.currentAuthor();}

// in class Authorpublic boolean currentAuthor() {

return this.birthYear >= 1940;}

Page 90: Section3 containment and methods

currentAuthor() Unit testing

90

public void testCurrentAuthor() {Author felleisen = new Author("Matthias Felleisen", 1960);Book htdch = new Book(felleisen,

"How to Design Class Hierarchies", 0.0, 2004);assertTrue(htdch.currentAuthor());

Author friedman = new Author("Daniel P. Friedman", 1939);Book aljafp = new Book(friedman,

"A Little Java, A Few Pattern", 25.9, 1998);assertFalse(aljafp.currentAuthor());

}

Page 91: Section3 containment and methods

thisAuthor()

• Method implementation

91

// in class Bookpublic boolean thisAuthor(Author that) {

return this.author.same(that);}

// in class Authorpublic boolean same(Author that) {

return (this.name.equals(that.name)) &&(this.birthYear == that.birthYear);

}

Page 92: Section3 containment and methods

thisAuthor() Unit testing

92

public void testThisAuthor() {

Author felleisen = new Author("Matthias Felleisen", 1960);

Book htdch = new Book(felleisen,

"How to Design Class Hierarchies", 0.0, 2004);

assertTrue(htdch.thisAuthor(felleisen));

Author friedman = new Author("Daniel P. Friedman", 1939);

assertFalse(htdch.thisAuthor(friedman));

}

Page 93: Section3 containment and methods

sameAuthor()

• Method implementation

93

// in class Bookpublic boolean sameAuthor(Book that) {

return this.author.same(that.author);}

Page 94: Section3 containment and methods

sameAuthor()

• Unit testing

94

public void testSameAuthor() {Author felleisen = new Author("Matthias Felleisen", 1960);Book htdch = new Book(felleisen,

"How to Design Class Hierarchies", 0.0, 2004);Book htdp = new Book(felleisen,

"How to Design Programs", 0.0, 2002);assertTrue(htdch.sameAuthor(htdp));

Author friedman = new Author("Daniel P. Friedman", 1939);Book aljafp = new Book(friedman,

"A Little Java, A Few Pattern", 25.9, 1998);assertFalse(aljafp.sameAuthor(htdch));

}

Page 95: Section3 containment and methods

sameGeneration()

• Method implementation

95

// in class Bookpublic boolean sameGeneration(Book that) {

return this.author.sameGeneration(that.author);}

// in class Authorpublic boolean sameGeneration(Author that) {

return Math.abs(this.birthYear - that.birthYear) <= 10;}

Page 96: Section3 containment and methods

sameGeneration() Unit testing

96Back

public void testSameGeneration() {Author felleisen = new Author("Matthias Felleisen", 1960);Book htdch = new Book(felleisen,

"How to Design Class Hierarchies", 0.0, 2004);assertTrue(htdch.sameGeneration(htdp));

Author friedman = new Author("Daniel P. Friedman", 1939);Book aljafp = new Book(friedman,

"A Little Java, A Few Pattern", 25.9, 1998);assertFalse(aljafp.sameGeneration(htdch));

}

Page 97: Section3 containment and methods

Solution 4.1.2

97

Page 98: Section3 containment and methods

withinRange()

98Back

public class WeatherRecord {...public boolean withinRange() {

return this.today.within(this.normal);}

public boolean rainyDay(double thatPrecipitation) {return this.precipitation >= thatPrecipitation;

}

public boolean recordDay() {return !this.today.within(this.record);

}} public class TemperatureRange {

private double low;private double high;public boolean within(TemperatureRange that) {

return (this.low >= that.low) && (this.high <= that.high);

}}

Page 99: Section3 containment and methods

Solution 4.1.3

99