SlideShare a Scribd company logo
1 of 99
Download to read offline
Class References, Object
Containment and Methods
1
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 distance
of the day's run, the duration of the run, and a comment
describing the runner's post-run feeling.
2
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
Class Diagram
4
Entry
- Date date
- double distance
- int duration
- String comment
Date
- int day
- int month
- int year
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
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");
}
}
Methods for containment
7
Add methods to the Entry
8
??? nnn(???)
Entry
- Date date
- double distance
- int duration
- String comment
Date
- int day
- int month
- int year
??? kkk(???)
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...
}
}
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...
}
}
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
Design pace() method
• Purpose and contract (method signature)
// computes the pace for a daily entry
public 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
Design pace() method (con't)
13
public double pace() {
return this.duration / this.distance;
}
// computes the pace for a daily entry
public double pace() {
...this.date...
...this.duration...
...this.distance...
...this.comment...
}
Template
Implement
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);
}
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
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
Design earlierThan() method
• Purpose and contract (method signature)
// is this date early than the other date
public 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
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
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));
}
}
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
Class Diagram
21
Restaurant
- String name
- String food
- String priceRange
- Intersection intersection
Intersection
- int avenue
- int street
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
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)
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
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
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 another
public boolean closeTo(Intersection that) {
...this.avenue...
...this.street...
...that.avenue...
...that.street...
}
}
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 another
public boolean closeTo(Restaurant that) {
...this.name...
...this.food...
...this.priceRange...
...this.intersection.closeTo(...)...
...that.name...
...that.food...
...that.priceRange...
...that.intersection.closeTo(...)...
}
}
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);
}
}
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));
}
Relax &
…Do Exercises …
30
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
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
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
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()
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 5
q.distanceToO() // should produce 13
r.distanceToO() // should produce 5
s.distanceToO() // should produce 13
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 origin
public double distanceToO() { ... }
}
distanceToO – Template
37
public class CartPt {
...
// to compute the distance of this point to the origin
public double distanceToO() {
...this.x...
...this.y...
}
}
public class Rectangle {
...
// to compute the distance of this Rectangle to the origin
public double distanceToO() {
...this.nwCorner.distanceToO()...
...this.width...
...this.height...
}
}
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 origin
public 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.
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();
}
}
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);
}
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
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.
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
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?
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()
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
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()
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 origin
public doublle distanceToO() {
...this.center.distanceToO()...this.center.getX()...
...this.center.getY()...
...this.radius...
}
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 origin
public double distanceToO() {
return this.center.distanceToO();
}
}
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);
}
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 circle
public double perimeter () {
...this.distanceToO()...
...this.center.distanceToO()
...this.center.getX()...this.center.getY()...
...this.radius...
}
}
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;
}
}
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);
}
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 circle
public double area () {
...this.distanceToO()...
...this.perimeter()...
...this.center.distanceToO()...this.center.getX()...
...this.center.getY()...
...this.radius...
}
}
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;
}
}
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);
}
Area of ring
57
X
y
Y
0
x
Area of ring
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 ring
public double area(Circle that) {
...this.center...this.radius...
...this.distanceToO()...this.perimeter()...this.area()...
...that.center...that.radius...
...that.distanceToO()...that.perimeter()...that.area()...
}
}
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());
}
}
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);
}
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
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()
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()
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 cylinder
public double volume() {
...this.baseDisk.distanceToO()
...this.baseDisk.perimeter()...this.baseDisk.area()...
...this.height...
}
}
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 cylinder
public double volume() {
return this.baseDisk.area() * this.height;
}
}
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);
}
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 cylinder
public double surface(){
...this.baseDisk.distanceToO()
...this.baseDisk.perimeter()...this.baseDisk.area()...
...this.height...
}
}
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 cylinder
public double volume() {
return this.baseDisk.area() * this.height;
}
// Compute the surface of the cylinder
public double surface() {
return this.baseDisk.perimeter() * this.height;
}
}
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);
}
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()
Exercises
71
• Part III: Exercise 3.1.3 (HTDCH)
• Exercise 4.1.1 to 4.1.2 (HTDCH)
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
• 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
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.
74
Solution
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
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
Relax &
…Do Exercises …
77
Solution 3.1.3
78
House
-String kind
-int nRooms
-Address address
-int price
Address
-String houseNumber
-String street
-String city
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;
}
...
}
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
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
inThisCity()
82
// class Address
public boolean inThisCity(String thatCity) {
return this.city.equals(thatCity);
}
// class House
public boolean inThisCity(String city) {
return this.address.inThisCity(city);
}
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"));
}
sameCity()
84
// class House
public boolean sameCity(House that) {
return this.address.sameCity(that.address);
}
// class Address
public boolean sameCity(Address that) {
return this.city.equals(that.city);
}
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));
}
Solution 4.1.1
86
Book
-String title
-double price
-int publishYear
-Author author
Author
-String name
-int birthYear
currentBook()
• Method implementation
87
public boolean currentBook() {
return (this.publishYear == 2004) ||
(this.publishYear == 2003);
}
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());
}
currentAuthor()
• Method implementation
89
// in class Book
public boolean currentAuthor() {
return this.author.currentAuthor();
}
// in class Author
public boolean currentAuthor() {
return this.birthYear >= 1940;
}
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());
}
thisAuthor()
• Method implementation
91
// in class Book
public boolean thisAuthor(Author that) {
return this.author.same(that);
}
// in class Author
public boolean same(Author that) {
return (this.name.equals(that.name)) &&
(this.birthYear == that.birthYear);
}
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));
}
sameAuthor()
• Method implementation
93
// in class Book
public boolean sameAuthor(Book that) {
return this.author.same(that.author);
}
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));
}
sameGeneration()
• Method implementation
95
// in class Book
public boolean sameGeneration(Book that) {
return this.author.sameGeneration(that.author);
}
// in class Author
public boolean sameGeneration(Author that) {
return Math.abs(this.birthYear - that.birthYear) <= 10;
}
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));
}
Solution 4.1.2
97
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);
}
}
Solution 4.1.3
99

More Related Content

What's hot

Appendix of downlink coverage probability in heterogeneous cellular networks ...
Appendix of downlink coverage probability in heterogeneous cellular networks ...Appendix of downlink coverage probability in heterogeneous cellular networks ...
Appendix of downlink coverage probability in heterogeneous cellular networks ...Cora Li
 
Maneuvering target track prediction model
Maneuvering target track prediction modelManeuvering target track prediction model
Maneuvering target track prediction modelIJCI JOURNAL
 
Appendix of heterogeneous cellular network user distribution model
Appendix of heterogeneous cellular network user distribution modelAppendix of heterogeneous cellular network user distribution model
Appendix of heterogeneous cellular network user distribution modelCora Li
 
International journal of engineering issues vol 2015 - no 1 - paper4
International journal of engineering issues   vol 2015 - no 1 - paper4International journal of engineering issues   vol 2015 - no 1 - paper4
International journal of engineering issues vol 2015 - no 1 - paper4sophiabelthome
 
Context-Aware Recommender System Based on Boolean Matrix Factorisation
Context-Aware Recommender System Based on Boolean Matrix FactorisationContext-Aware Recommender System Based on Boolean Matrix Factorisation
Context-Aware Recommender System Based on Boolean Matrix FactorisationDmitrii Ignatov
 
On Certain Special Vector Fields in a Finsler Space III
On Certain Special Vector Fields in a Finsler Space IIIOn Certain Special Vector Fields in a Finsler Space III
On Certain Special Vector Fields in a Finsler Space IIIBRNSS Publication Hub
 
Radix-3 Algorithm for Realization of Discrete Fourier Transform
Radix-3 Algorithm for Realization of Discrete Fourier TransformRadix-3 Algorithm for Realization of Discrete Fourier Transform
Radix-3 Algorithm for Realization of Discrete Fourier TransformIJERA Editor
 
ENHANCEMENT OF TRANSMISSION RANGE ASSIGNMENT FOR CLUSTERED WIRELESS SENSOR NE...
ENHANCEMENT OF TRANSMISSION RANGE ASSIGNMENT FOR CLUSTERED WIRELESS SENSOR NE...ENHANCEMENT OF TRANSMISSION RANGE ASSIGNMENT FOR CLUSTERED WIRELESS SENSOR NE...
ENHANCEMENT OF TRANSMISSION RANGE ASSIGNMENT FOR CLUSTERED WIRELESS SENSOR NE...IJCNCJournal
 
Otter 2016-11-14-ss
Otter 2016-11-14-ssOtter 2016-11-14-ss
Otter 2016-11-14-ssRuo Ando
 
Skiena algorithm 2007 lecture15 backtracing
Skiena algorithm 2007 lecture15 backtracingSkiena algorithm 2007 lecture15 backtracing
Skiena algorithm 2007 lecture15 backtracingzukun
 
A method of transformation for generalized hypergeometric function 2 f2
A method of transformation for generalized hypergeometric function 2 f2A method of transformation for generalized hypergeometric function 2 f2
A method of transformation for generalized hypergeometric function 2 f2Alexander Decker
 
Specific Finite Groups(General)
Specific Finite Groups(General)Specific Finite Groups(General)
Specific Finite Groups(General)Shane Nicklas
 
Point symmetries of lagrangians
Point symmetries of lagrangiansPoint symmetries of lagrangians
Point symmetries of lagrangiansorajjournal
 
LeetCode Solutions In Java .pdf
LeetCode Solutions In Java .pdfLeetCode Solutions In Java .pdf
LeetCode Solutions In Java .pdfzupsezekno
 
Simpli fied Solutions of the CLP and CCP Limiting Cases of the Problem of Apo...
Simplified Solutions of the CLP and CCP Limiting Cases of the Problem of Apo...Simplified Solutions of the CLP and CCP Limiting Cases of the Problem of Apo...
Simpli fied Solutions of the CLP and CCP Limiting Cases of the Problem of Apo...James Smith
 
Radix-2 Algorithms for realization of Type-II Discrete Sine Transform and Typ...
Radix-2 Algorithms for realization of Type-II Discrete Sine Transform and Typ...Radix-2 Algorithms for realization of Type-II Discrete Sine Transform and Typ...
Radix-2 Algorithms for realization of Type-II Discrete Sine Transform and Typ...IJERA Editor
 
FURTHER RESULTS ON THE DIRAC DELTA APPROXIMATION AND THE MOMENT GENERATING FU...
FURTHER RESULTS ON THE DIRAC DELTA APPROXIMATION AND THE MOMENT GENERATING FU...FURTHER RESULTS ON THE DIRAC DELTA APPROXIMATION AND THE MOMENT GENERATING FU...
FURTHER RESULTS ON THE DIRAC DELTA APPROXIMATION AND THE MOMENT GENERATING FU...IJCNC
 

What's hot (19)

Appendix of downlink coverage probability in heterogeneous cellular networks ...
Appendix of downlink coverage probability in heterogeneous cellular networks ...Appendix of downlink coverage probability in heterogeneous cellular networks ...
Appendix of downlink coverage probability in heterogeneous cellular networks ...
 
Maneuvering target track prediction model
Maneuvering target track prediction modelManeuvering target track prediction model
Maneuvering target track prediction model
 
Appendix of heterogeneous cellular network user distribution model
Appendix of heterogeneous cellular network user distribution modelAppendix of heterogeneous cellular network user distribution model
Appendix of heterogeneous cellular network user distribution model
 
International journal of engineering issues vol 2015 - no 1 - paper4
International journal of engineering issues   vol 2015 - no 1 - paper4International journal of engineering issues   vol 2015 - no 1 - paper4
International journal of engineering issues vol 2015 - no 1 - paper4
 
Context-Aware Recommender System Based on Boolean Matrix Factorisation
Context-Aware Recommender System Based on Boolean Matrix FactorisationContext-Aware Recommender System Based on Boolean Matrix Factorisation
Context-Aware Recommender System Based on Boolean Matrix Factorisation
 
On Certain Special Vector Fields in a Finsler Space III
On Certain Special Vector Fields in a Finsler Space IIIOn Certain Special Vector Fields in a Finsler Space III
On Certain Special Vector Fields in a Finsler Space III
 
Quiz 1
Quiz 1Quiz 1
Quiz 1
 
Radix-3 Algorithm for Realization of Discrete Fourier Transform
Radix-3 Algorithm for Realization of Discrete Fourier TransformRadix-3 Algorithm for Realization of Discrete Fourier Transform
Radix-3 Algorithm for Realization of Discrete Fourier Transform
 
ENHANCEMENT OF TRANSMISSION RANGE ASSIGNMENT FOR CLUSTERED WIRELESS SENSOR NE...
ENHANCEMENT OF TRANSMISSION RANGE ASSIGNMENT FOR CLUSTERED WIRELESS SENSOR NE...ENHANCEMENT OF TRANSMISSION RANGE ASSIGNMENT FOR CLUSTERED WIRELESS SENSOR NE...
ENHANCEMENT OF TRANSMISSION RANGE ASSIGNMENT FOR CLUSTERED WIRELESS SENSOR NE...
 
Presentation OCIP2014
Presentation OCIP2014Presentation OCIP2014
Presentation OCIP2014
 
Otter 2016-11-14-ss
Otter 2016-11-14-ssOtter 2016-11-14-ss
Otter 2016-11-14-ss
 
Skiena algorithm 2007 lecture15 backtracing
Skiena algorithm 2007 lecture15 backtracingSkiena algorithm 2007 lecture15 backtracing
Skiena algorithm 2007 lecture15 backtracing
 
A method of transformation for generalized hypergeometric function 2 f2
A method of transformation for generalized hypergeometric function 2 f2A method of transformation for generalized hypergeometric function 2 f2
A method of transformation for generalized hypergeometric function 2 f2
 
Specific Finite Groups(General)
Specific Finite Groups(General)Specific Finite Groups(General)
Specific Finite Groups(General)
 
Point symmetries of lagrangians
Point symmetries of lagrangiansPoint symmetries of lagrangians
Point symmetries of lagrangians
 
LeetCode Solutions In Java .pdf
LeetCode Solutions In Java .pdfLeetCode Solutions In Java .pdf
LeetCode Solutions In Java .pdf
 
Simpli fied Solutions of the CLP and CCP Limiting Cases of the Problem of Apo...
Simplified Solutions of the CLP and CCP Limiting Cases of the Problem of Apo...Simplified Solutions of the CLP and CCP Limiting Cases of the Problem of Apo...
Simpli fied Solutions of the CLP and CCP Limiting Cases of the Problem of Apo...
 
Radix-2 Algorithms for realization of Type-II Discrete Sine Transform and Typ...
Radix-2 Algorithms for realization of Type-II Discrete Sine Transform and Typ...Radix-2 Algorithms for realization of Type-II Discrete Sine Transform and Typ...
Radix-2 Algorithms for realization of Type-II Discrete Sine Transform and Typ...
 
FURTHER RESULTS ON THE DIRAC DELTA APPROXIMATION AND THE MOMENT GENERATING FU...
FURTHER RESULTS ON THE DIRAC DELTA APPROXIMATION AND THE MOMENT GENERATING FU...FURTHER RESULTS ON THE DIRAC DELTA APPROXIMATION AND THE MOMENT GENERATING FU...
FURTHER RESULTS ON THE DIRAC DELTA APPROXIMATION AND THE MOMENT GENERATING FU...
 

Viewers also liked

Section1 compound data class
Section1 compound data classSection1 compound data class
Section1 compound data classDương Tùng
 
108-113 CV Hazirlama
108-113 CV Hazirlama108-113 CV Hazirlama
108-113 CV HazirlamaB Mutlu
 
La guerrillera holandesa que negociará por las
La guerrillera holandesa que negociará por lasLa guerrillera holandesa que negociará por las
La guerrillera holandesa que negociará por lasmarlenmarias123456
 
Section0 course introduction
Section0 course introductionSection0 course introduction
Section0 course introductionDương Tùng
 
LENOVO THINKSERVER RVD 08 MASTER EXAM certificate
LENOVO THINKSERVER RVD 08 MASTER EXAM certificateLENOVO THINKSERVER RVD 08 MASTER EXAM certificate
LENOVO THINKSERVER RVD 08 MASTER EXAM certificateAntonio Muguersia
 
IAB BRASÍLIA: Mobile connections - João Carvalho
IAB BRASÍLIA: Mobile connections - João CarvalhoIAB BRASÍLIA: Mobile connections - João Carvalho
IAB BRASÍLIA: Mobile connections - João CarvalhoIAB Brasil
 
Tic para todos y todas
Tic para todos y todasTic para todos y todas
Tic para todos y todasUASD
 
Section2 methods for classes
Section2 methods for classesSection2 methods for classes
Section2 methods for classesDương Tùng
 

Viewers also liked (11)

Section1 compound data class
Section1 compound data classSection1 compound data class
Section1 compound data class
 
108-113 CV Hazirlama
108-113 CV Hazirlama108-113 CV Hazirlama
108-113 CV Hazirlama
 
La guerrillera holandesa que negociará por las
La guerrillera holandesa que negociará por lasLa guerrillera holandesa que negociará por las
La guerrillera holandesa que negociará por las
 
Section0 course introduction
Section0 course introductionSection0 course introduction
Section0 course introduction
 
LENOVO THINKSERVER RVD 08 MASTER EXAM certificate
LENOVO THINKSERVER RVD 08 MASTER EXAM certificateLENOVO THINKSERVER RVD 08 MASTER EXAM certificate
LENOVO THINKSERVER RVD 08 MASTER EXAM certificate
 
НАШ САД
НАШ САДНАШ САД
НАШ САД
 
IAB BRASÍLIA: Mobile connections - João Carvalho
IAB BRASÍLIA: Mobile connections - João CarvalhoIAB BRASÍLIA: Mobile connections - João Carvalho
IAB BRASÍLIA: Mobile connections - João Carvalho
 
Tic para todos y todas
Tic para todos y todasTic para todos y todas
Tic para todos y todas
 
Section2 methods for classes
Section2 methods for classesSection2 methods for classes
Section2 methods for classes
 
Subir videos a Youtube
Subir videos a YoutubeSubir videos a Youtube
Subir videos a Youtube
 
Facto e opinião
Facto e opiniãoFacto e opinião
Facto e opinião
 

Similar to Section3 containment and methods

New Java Date/Time API
New Java Date/Time APINew Java Date/Time API
New Java Date/Time APIJuliet Nkwor
 
Code level change propagation in virtual platform
Code level change propagation in virtual platformCode level change propagation in virtual platform
Code level change propagation in virtual platformHaiderAli650468
 
ch04-conditional-execution.ppt
ch04-conditional-execution.pptch04-conditional-execution.ppt
ch04-conditional-execution.pptMahyuddin8
 
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfLECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfShashikantSathe3
 
Java assignment 1
Java assignment 1Java assignment 1
Java assignment 1Daman Toor
 
A Hybrid Data Clustering Approach using K-Means and Simplex Method-based Bact...
A Hybrid Data Clustering Approach using K-Means and Simplex Method-based Bact...A Hybrid Data Clustering Approach using K-Means and Simplex Method-based Bact...
A Hybrid Data Clustering Approach using K-Means and Simplex Method-based Bact...IRJET Journal
 
USING CUCKOO ALGORITHM FOR ESTIMATING TWO GLSD PARAMETERS AND COMPARING IT WI...
USING CUCKOO ALGORITHM FOR ESTIMATING TWO GLSD PARAMETERS AND COMPARING IT WI...USING CUCKOO ALGORITHM FOR ESTIMATING TWO GLSD PARAMETERS AND COMPARING IT WI...
USING CUCKOO ALGORITHM FOR ESTIMATING TWO GLSD PARAMETERS AND COMPARING IT WI...AIRCC Publishing Corporation
 
Using Cuckoo Algorithm for Estimating Two GLSD Parameters and Comparing it wi...
Using Cuckoo Algorithm for Estimating Two GLSD Parameters and Comparing it wi...Using Cuckoo Algorithm for Estimating Two GLSD Parameters and Comparing it wi...
Using Cuckoo Algorithm for Estimating Two GLSD Parameters and Comparing it wi...AIRCC Publishing Corporation
 
USING CUCKOO ALGORITHM FOR ESTIMATING TWO GLSD PARAMETERS AND COMPARING IT WI...
USING CUCKOO ALGORITHM FOR ESTIMATING TWO GLSD PARAMETERS AND COMPARING IT WI...USING CUCKOO ALGORITHM FOR ESTIMATING TWO GLSD PARAMETERS AND COMPARING IT WI...
USING CUCKOO ALGORITHM FOR ESTIMATING TWO GLSD PARAMETERS AND COMPARING IT WI...ijcsit
 
Managing Uncertainties in Hardware-Software Codesign Projects
Managing Uncertainties in Hardware-Software Codesign ProjectsManaging Uncertainties in Hardware-Software Codesign Projects
Managing Uncertainties in Hardware-Software Codesign ProjectsJones Albuquerque
 
Functional Reactive Programming with RxJS
Functional Reactive Programming with RxJSFunctional Reactive Programming with RxJS
Functional Reactive Programming with RxJSstefanmayer13
 
Dimensional performance benchmarking of SQL
Dimensional performance benchmarking of SQLDimensional performance benchmarking of SQL
Dimensional performance benchmarking of SQLBrendan Furey
 

Similar to Section3 containment and methods (20)

New Java Date/Time API
New Java Date/Time APINew Java Date/Time API
New Java Date/Time API
 
Code level change propagation in virtual platform
Code level change propagation in virtual platformCode level change propagation in virtual platform
Code level change propagation in virtual platform
 
IPA Fall Days 2019
 IPA Fall Days 2019 IPA Fall Days 2019
IPA Fall Days 2019
 
ch04-conditional-execution.ppt
ch04-conditional-execution.pptch04-conditional-execution.ppt
ch04-conditional-execution.ppt
 
Methods
MethodsMethods
Methods
 
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfLECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
 
Kpi driven-java-development-fn conf
Kpi driven-java-development-fn confKpi driven-java-development-fn conf
Kpi driven-java-development-fn conf
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
BIRTE-13-Kawashima
BIRTE-13-KawashimaBIRTE-13-Kawashima
BIRTE-13-Kawashima
 
Java assignment 1
Java assignment 1Java assignment 1
Java assignment 1
 
A Hybrid Data Clustering Approach using K-Means and Simplex Method-based Bact...
A Hybrid Data Clustering Approach using K-Means and Simplex Method-based Bact...A Hybrid Data Clustering Approach using K-Means and Simplex Method-based Bact...
A Hybrid Data Clustering Approach using K-Means and Simplex Method-based Bact...
 
06slide.ppt
06slide.ppt06slide.ppt
06slide.ppt
 
USING CUCKOO ALGORITHM FOR ESTIMATING TWO GLSD PARAMETERS AND COMPARING IT WI...
USING CUCKOO ALGORITHM FOR ESTIMATING TWO GLSD PARAMETERS AND COMPARING IT WI...USING CUCKOO ALGORITHM FOR ESTIMATING TWO GLSD PARAMETERS AND COMPARING IT WI...
USING CUCKOO ALGORITHM FOR ESTIMATING TWO GLSD PARAMETERS AND COMPARING IT WI...
 
Using Cuckoo Algorithm for Estimating Two GLSD Parameters and Comparing it wi...
Using Cuckoo Algorithm for Estimating Two GLSD Parameters and Comparing it wi...Using Cuckoo Algorithm for Estimating Two GLSD Parameters and Comparing it wi...
Using Cuckoo Algorithm for Estimating Two GLSD Parameters and Comparing it wi...
 
USING CUCKOO ALGORITHM FOR ESTIMATING TWO GLSD PARAMETERS AND COMPARING IT WI...
USING CUCKOO ALGORITHM FOR ESTIMATING TWO GLSD PARAMETERS AND COMPARING IT WI...USING CUCKOO ALGORITHM FOR ESTIMATING TWO GLSD PARAMETERS AND COMPARING IT WI...
USING CUCKOO ALGORITHM FOR ESTIMATING TWO GLSD PARAMETERS AND COMPARING IT WI...
 
Managing Uncertainties in Hardware-Software Codesign Projects
Managing Uncertainties in Hardware-Software Codesign ProjectsManaging Uncertainties in Hardware-Software Codesign Projects
Managing Uncertainties in Hardware-Software Codesign Projects
 
Functional Reactive Programming with RxJS
Functional Reactive Programming with RxJSFunctional Reactive Programming with RxJS
Functional Reactive Programming with RxJS
 
Java exercise1
Java exercise1Java exercise1
Java exercise1
 
Java Day-7
Java Day-7Java Day-7
Java Day-7
 
Dimensional performance benchmarking of SQL
Dimensional performance benchmarking of SQLDimensional performance benchmarking of SQL
Dimensional performance benchmarking of SQL
 

Recently uploaded

Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 

Recently uploaded (20)

Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 

Section3 containment and methods

  • 2. 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 distance of the day's run, the duration of the run, and a comment describing the runner's post-run feeling. 2
  • 3. 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
  • 4. Class Diagram 4 Entry - Date date - double distance - int duration - String comment Date - int day - int month - int year
  • 5. 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
  • 6. 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"); } }
  • 8. Add methods to the Entry 8 ??? nnn(???) Entry - Date date - double distance - int duration - String comment Date - int day - int month - int year ??? kkk(???)
  • 9. 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... } }
  • 10. 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... } }
  • 11. 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
  • 12. Design pace() method • Purpose and contract (method signature) // computes the pace for a daily entry public 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
  • 13. Design pace() method (con't) 13 public double pace() { return this.duration / this.distance; } // computes the pace for a daily entry public double pace() { ...this.date... ...this.duration... ...this.distance... ...this.comment... } Template Implement
  • 14. 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); }
  • 15. 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
  • 16. 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
  • 17. Design earlierThan() method • Purpose and contract (method signature) // is this date early than the other date public 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
  • 18. 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
  • 19. 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)); } }
  • 20. 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
  • 21. Class Diagram 21 Restaurant - String name - String food - String priceRange - Intersection intersection Intersection - int avenue - int street
  • 22. 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
  • 23. 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)
  • 24. 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
  • 25. 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
  • 26. 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 another public boolean closeTo(Intersection that) { ...this.avenue... ...this.street... ...that.avenue... ...that.street... } }
  • 27. 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 another public boolean closeTo(Restaurant that) { ...this.name... ...this.food... ...this.priceRange... ...this.intersection.closeTo(...)... ...that.name... ...that.food... ...that.priceRange... ...that.intersection.closeTo(...)... } }
  • 28. 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); } }
  • 29. 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)); }
  • 31. 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
  • 32. 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
  • 33. 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
  • 34. 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()
  • 35. 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 5 q.distanceToO() // should produce 13 r.distanceToO() // should produce 5 s.distanceToO() // should produce 13
  • 36. 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 origin public double distanceToO() { ... } }
  • 37. distanceToO – Template 37 public class CartPt { ... // to compute the distance of this point to the origin public double distanceToO() { ...this.x... ...this.y... } } public class Rectangle { ... // to compute the distance of this Rectangle to the origin public double distanceToO() { ...this.nwCorner.distanceToO()... ...this.width... ...this.height... } }
  • 38. 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 origin public 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.
  • 39. 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(); } }
  • 40. 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); }
  • 41. 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
  • 42. 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.
  • 43. 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
  • 44. 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?
  • 45. 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()
  • 46. 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
  • 47. 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()
  • 48. 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 origin public doublle distanceToO() { ...this.center.distanceToO()...this.center.getX()... ...this.center.getY()... ...this.radius... }
  • 49. 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 origin public double distanceToO() { return this.center.distanceToO(); } }
  • 50. 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); }
  • 51. 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 circle public double perimeter () { ...this.distanceToO()... ...this.center.distanceToO() ...this.center.getX()...this.center.getY()... ...this.radius... } }
  • 52. 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; } }
  • 53. 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); }
  • 54. 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 circle public double area () { ...this.distanceToO()... ...this.perimeter()... ...this.center.distanceToO()...this.center.getX()... ...this.center.getY()... ...this.radius... } }
  • 55. 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; } }
  • 56. 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); }
  • 58. 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 ring public double area(Circle that) { ...this.center...this.radius... ...this.distanceToO()...this.perimeter()...this.area()... ...that.center...that.radius... ...that.distanceToO()...that.perimeter()...that.area()... } }
  • 59. 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()); } }
  • 60. 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); }
  • 61. 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
  • 62. 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()
  • 63. 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()
  • 64. 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 cylinder public double volume() { ...this.baseDisk.distanceToO() ...this.baseDisk.perimeter()...this.baseDisk.area()... ...this.height... } }
  • 65. 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 cylinder public double volume() { return this.baseDisk.area() * this.height; } }
  • 66. 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); }
  • 67. 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 cylinder public double surface(){ ...this.baseDisk.distanceToO() ...this.baseDisk.perimeter()...this.baseDisk.area()... ...this.height... } }
  • 68. 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 cylinder public double volume() { return this.baseDisk.area() * this.height; } // Compute the surface of the cylinder public double surface() { return this.baseDisk.perimeter() * this.height; } }
  • 69. 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); }
  • 70. 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()
  • 71. Exercises 71 • Part III: Exercise 3.1.3 (HTDCH) • Exercise 4.1.1 to 4.1.2 (HTDCH)
  • 72. 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
  • 73. • 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
  • 74. 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. 74 Solution
  • 75. 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
  • 76. 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
  • 78. Solution 3.1.3 78 House -String kind -int nRooms -Address address -int price Address -String houseNumber -String street -String city
  • 79. 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; } ... }
  • 80. 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
  • 81. 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
  • 82. inThisCity() 82 // class Address public boolean inThisCity(String thatCity) { return this.city.equals(thatCity); } // class House public boolean inThisCity(String city) { return this.address.inThisCity(city); }
  • 83. 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")); }
  • 84. sameCity() 84 // class House public boolean sameCity(House that) { return this.address.sameCity(that.address); } // class Address public boolean sameCity(Address that) { return this.city.equals(that.city); }
  • 85. 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)); }
  • 86. Solution 4.1.1 86 Book -String title -double price -int publishYear -Author author Author -String name -int birthYear
  • 87. currentBook() • Method implementation 87 public boolean currentBook() { return (this.publishYear == 2004) || (this.publishYear == 2003); }
  • 88. 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()); }
  • 89. currentAuthor() • Method implementation 89 // in class Book public boolean currentAuthor() { return this.author.currentAuthor(); } // in class Author public boolean currentAuthor() { return this.birthYear >= 1940; }
  • 90. 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()); }
  • 91. thisAuthor() • Method implementation 91 // in class Book public boolean thisAuthor(Author that) { return this.author.same(that); } // in class Author public boolean same(Author that) { return (this.name.equals(that.name)) && (this.birthYear == that.birthYear); }
  • 92. 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)); }
  • 93. sameAuthor() • Method implementation 93 // in class Book public boolean sameAuthor(Book that) { return this.author.same(that.author); }
  • 94. 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)); }
  • 95. sameGeneration() • Method implementation 95 // in class Book public boolean sameGeneration(Book that) { return this.author.sameGeneration(that.author); } // in class Author public boolean sameGeneration(Author that) { return Math.abs(this.birthYear - that.birthYear) <= 10; }
  • 96. 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)); }
  • 98. 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); } }