section5 containment in unions and methods

162
Containment in Unions and Methods 1

Upload: duong-tung

Post on 16-Apr-2017

255 views

Category:

Education


8 download

TRANSCRIPT

Page 1: Section5 containment in unions and methods

Containment in Unions

and Methods

1

Page 2: Section5 containment in unions and methods

List Structure

2

Page 3: Section5 containment in unions and methods

Managing Inventory

• A sales clerk in a toy store needs to know not only the name of the toy, but also its price, warehouse availability.

• The representation of an inventory as a list of toys.

3

Page 4: Section5 containment in unions and methods

Data definition

• Inventory is one of:– a empty– a construct of Toy Inventory

• The class of Inventory is a union: – Inventory, which is the type of all kind of inventories; – MTInventory, which represents an empty inventory;

and – ConsInventory, which represents the construction of

a new inventory from a Toy and an existing Inventory.

4

Page 5: Section5 containment in unions and methods

Class diagram

• An MTInventoryclass don't have any fields for it.

• A ConsInventoryclass requires two field definitions: one for the first Toy and one for the rest of the Inventory.

5

self-referential

MTInventory

Toy- String name- double price- int available

ConsInventory- Toy first- Inventory rest

Inventory

Page 6: Section5 containment in unions and methods

Define classes an constructors

6

public interface Inventory { }

public class MTInventory implements Inventory {}

public class ConsInventory implements Inventory {private Toy first;private Inventory rest;public ConsInventory(Toy first, Inventory rest ) {

this.first = first;this.rest= rest;

}}

Page 7: Section5 containment in unions and methods

Define classes and constructors

7

public class Toy {private String name;private double price;private int available;

public Toy(String name, double price, int available) {

this.name = name;this.price = price;this.available = available;

}}

Page 8: Section5 containment in unions and methods

Test Constructor

8

public class InventoryTest extends TestCase {public void testConstructor() {

Toy doll = new Toy("doll", 17.95, 5);Toy robot = new Toy("robot", 22.05, 3);Toy gun = new Toy ("gun", 15.0, 4);

Inventory empty = new MTInventory();Inventory i1 = new ConsInventory(doll, empty);Inventory i2 = new ConsInventory(robot, i1);Inventory i3 = new ConsInventory(gun, i2);System.out.println(i3);

Inventory all = new ConsInventory(doll, new ConsInventory(robot, new ConsInventory(gun, new MTInventory())));

System.out.println(all);}

}

Page 9: Section5 containment in unions and methods

Print the content of an inventory

Q: How can we print the content of an object.

A: overwriting toString() method of class Object.

Q: Do we need to add toString() in Inventoryclass?

A: No !

9

Page 10: Section5 containment in unions and methods

toString() in classes

10

// inside of MTInventory classpublic String toString() {

return "";}

// inside of ConsInventory class public String toString() {

return this.first.toString() + "\n"+ this.rest.toString();

}

// inside of Toy class public String toString() {

return "name: " + this.name+ ", price: " + this.price+ ", available: " + this.available;

}}

Page 11: Section5 containment in unions and methods

Employee problem (again)

• The accountant wants to compute the wage of not only an employee but also all employees in the company.

• Similarly, representing all employees is a list of employees.

11

Page 12: Section5 containment in unions and methods

Data definition

• The class of list of Employee is a union: – ILoEmployee, which is the type of all kind of

Employee list; – MTLoEmployee, which represents an empty list; and – ConsLoEmployee, which represents the construction

of a new list from an Employee and an existing list of Employee.

12

Page 13: Section5 containment in unions and methods

Class diagram

13

self-referential

MTLoEmployee

Employee- String name- int hours

ConsLoEmployee- Employee first- ILoEmployee rest

ILoEmployee

Page 14: Section5 containment in unions and methods

Define classes an constructors

14

public interface ILoEmployee {}

public class MTLoEmployee implements ILoEmployee {}

public class ConsLoEmployee implements ILoEmployee {private Employee first;private ILoEmployee rest;public ConsLoEmployee(Employee first, ILoEmployee rest) {

this.first = first;this.rest = rest;

}}

Page 15: Section5 containment in unions and methods

Define classes and constructors

15

//class Employeepublic class Employee {

private String name;private int hours;

public Employee(String name, int hours) {this.name = name;this.hours = hours;

}}

Page 16: Section5 containment in unions and methods

Test Constructor

16

public class ALoEmployeeTest extends TestCase {public void testConstructor() {

Employee nam = new Employee("Nam", 40);Employee mai = new Employee("Mai", 30);Employee minh = new Employee("Minh", 102);

ILoEmployee empty = new MTLoEmployee();ILoEmployee l1 = new ConsLoEmployee(nam, empty);ILoEmployee l2 = new ConsLoEmployee(mai, l1);ILoEmployee l3 = new ConsLoEmployee(minh, l2);System.out.println(l3);

ILoEmployee all = new ConsLoEmployee(nam, new ConsLoEmployee(mai, new ConsLoEmployee(minh, new MTLoEmployee())));

System.out.println(all);}

}

Page 17: Section5 containment in unions and methods

toString() method

17

// inside of MTLoEmployee class public String toString() {

return "";}

// inside of ConsLoEmployee classpublic String toString() {

return this.first.toString() + "\n"+ this.rest.toString();

}

// inside of Employee class public String toString() {

return "name: " + this.name+ ", hours: " + this.hours;

}

Page 18: Section5 containment in unions and methods

Containment in union – Part 1

18

Page 19: Section5 containment in unions and methods

Managing a Runner’s Logs Example

• 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 disposition.

• Naturally the program shouldn't just deal with a single log entry but sequences of log entries.

19

Page 20: Section5 containment in unions and methods

Data definition

• The class of Logs is a union: – ILog, which is the type of all logs; – MTLog, which represents an empty log; and – ConsLog, which represents the construction of a new

log from an entry and an existing log.

20

Page 21: Section5 containment in unions and methods

Class diagram

21

self-referential

MTLogDate

- int day- int month- int year

Entry

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

ILog

ConsLog

- Entry first- ILog rest

Page 22: Section5 containment in unions and methods

Define classes an constructors

22

public interface ILog {}

public class MTLog implements ILog {}

public class ConsLog implements ILog {private Entry first;private ILog rest;public ConsLog(Entry first, ILog rest) {

this.first = first;this.rest = rest;

}}

Page 23: Section5 containment in unions and methods

Define classes and constructors

23

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;

}}

Page 24: Section5 containment in unions and methods

Define classes and constructors

24

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;

}}

Page 25: Section5 containment in unions and methods

Test Constructor

25

public class LogTest extends TestCase {public void testConstructor() {

Entry e1 = new Entry(new Date(5, 5, 2005), 5.0, 25, "Good");

Entry e2 = new Entry(new Date(6, 6, 2005), 3.0, 24, "Tired");

Entry e3 = new Entry(new Date(23, 6, 2005), 26.0, 156, "Great");

ILog empty = new MTLog();ILog l1 = new ConsLog(e1, empty);ILog l2 = new ConsLog(e2, l1);ILog l3 = new ConsLog(e3, l2);System.out.println(l3);

ILog all = new ConsLog(e1, new ConsLog(e2, new ConsLog(e3, new MTLog())));

System.out.println(all);}

}

Page 26: Section5 containment in unions and methods

toString() method

26

// inside of ConsLog class public String toString() {

return this.first.toString() + " \n" + this.rest.toString();}

// inside of MTLog class public String toString() {

return "";}

// inside of Entry class public String toString() {

return "date: " + this.date.toString() + ", distance: " + this.distance+ ", duration: " + this.duration+ ", comment: " + this.comment;

}

// inside of Date class public String toString() {

return this.day + "/" + this.month + "/" + this.year;}

Page 27: Section5 containment in unions and methods

Recall 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).

• Clearly, the visitor assistant should deal with lists of restaurants, not just individual restaurants. A visitor may, for example, wish to learn about all Chinese restaurants in a certain area or all German restaurants in a certain price range.

27

Page 28: Section5 containment in unions and methods

Class diagram

28

Restaurant

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

Intersection

- int avenue- int street

ILoRestaurant

MTLoRestaurant ConsLoRestaurant

- Restaurant first- ILoRestaurant rest

Page 29: Section5 containment in unions and methods

Define classes and constructors

29

public interface ILoRestaurant {}

public class MTLoRestaurant implements ILoRestaurant {}

public class ConsLoRestaurant implements ILoRestaurant {private Restaurant first;private ILoRestaurant rest;public ConsLoRestaurant(Restaurant first,

ILoRestaurant rest) {this.first = first;this.rest = rest;

}}

Page 30: Section5 containment in unions and methods

Define Restaurant class

30

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

String priceRange,Intersection intersection) {

this.name = name;this.food = food;this.priceRange = priceRange;this.intersection = intersection;

}}

Page 31: Section5 containment in unions and methods

Define Intersection class

31

public class Intersection {private int avenue;private int street;

public Intersection(int avenue, int street) {this.avenue = avenue;this.street = street;

}}

Page 32: Section5 containment in unions and methods

toString() method

32

// in class ConsLoRestaurantpublic String toString() {return this.first.toString() + " \n" + this.rest.toString();

}// in class MTLoRestaurantpublic String toString() {return "";

}

// in class Restaurantpublic String toString() {return "Name: " + this.name + ", food: " + this.food

+ ", range price: " + this.priceRange+ ", intersection: " + this.intersection.toString() + "\n"+ this.rest;

} } // in class Intersection

public String toString() {return "avenue: " + this.avenue

+ ", street: " + this.street;}

Page 33: Section5 containment in unions and methods

Test Constructor

33

public class ConsLoRestaurantTest extends TestCase {public void testConstructor() {Restaurant r1 = new Restaurant("Chez Nous",

"French", "exp.", new Intersection(7, 65)); Restaurant r2 = new Restaurant("Das Bier",

"German", "cheap", new Intersection(2, 86));Restaurant r3 = new Restaurant("Sun",

"Chinese", "cheap", new Intersection(10, 13));

ILoRestaurant empty = new MTLoRestaurant(); ILoRestaurant l1 = new ConsLoRestaurant(r1, empty);ILoRestaurant l2 = new ConsLoRestaurant(r2, l1);ILoRestaurant l3 = new ConsLoRestaurant(r3, l2); System.out.println(l3);

ILoRestaurant all = new ConsLoRestaurant(r1, new ConsLoRestaurant (r2, new ConsLoRestaurant(r3, new MTLoRestaurant())));

System.out.println(all); }

}

Page 34: Section5 containment in unions and methods

Bài tập

• Thông tin về điểm số của mỗi sinh viên được cho trong một bảng điểm. Mỗi bảng điểm (ScoreBoard) bao gồm tên sinh viên (name), khóa học (class), và một danh sách điểm số các môn học của sinh viên. Thông tin về điểm số (GradeRecord) của sinh viên bao gồm mã số môn học (number), tên môn học (title), số tín chỉ (credits) và điểm số (grade). – Ví dụ: một bảng điểm của sinh viên Tran Van Hoa, khóa

2009 gồm các mục điểm số:• 211, "Database Fundamentals", 3, 7.5• 220, "Basic Programming", 2, 5.0• 690, "Algorithms", 4, 7.0• 721, "Data Structure", 4, 8.0

34

Page 35: Section5 containment in unions and methods

Yêu cầu

Thiết kế dữ liệu để biểu diễn bảng điểm và điểm số của sinh viên.

– Viết phương thức howManyCredits để tính tổng số tín chỉ trong bảng điểm mà sinh viên đã đạt được.

– Viết phương thức gradeAverage để tính điểm trung bình của sinh viên bằng tổng của tích điểm số từng môn với số tín chỉ chia cho tổng số tín chỉ.

– Viết phương thức sortByGradeDec để sắp xếp bảng điểm số của sinh viên theo thứ tự điểm giảm dần.

– Viết phương thức greaterThanList để trả về danh sách mục điểm số của sinh viên có điểm lớn hơn một giá trị cho trước.

35

Page 36: Section5 containment in unions and methods

ScoreBoard class diagram

36

ScoreBoard

-String name-String class-ILoGrade loGrade

ILoGrade

MTLoGrade ConsLoGrade

-GradeRecord first-ILoGrade rest

GradeRecord

-int number-String title-int credits-double grade

Page 37: Section5 containment in unions and methods

Overlaying shape example

• Lists are by no means the only form of information that requires a self-referential class diagram. Let's take another look at the problem of drawing shapes

• Develop a drawing program that deals with at least three kinds of shapes: dots, squares, and circles. ...In addition, the program should also deal with overlaying shapes on each other. In the following figure, for example, we have superimposed a circle on the right side of a square:

• We could now also superimpose (thêm vào) this compounded shape on another shape and so on.

37

Page 38: Section5 containment in unions and methods

Old class design

38

AShape

# CartPt location

CartPt

- int x- int y

Dot Circle

- int radius

Square

- int size

Rectangle

- int width- int height

Page 39: Section5 containment in unions and methods

Class Diagram

39

SingleShape

# CartPt location

CartPt

- int x- int y

Dot Circle

- int radius

Square

- int size

Rectangle

- int width- int height

CompositeShape

- IShape top- IShape bottom

IShape

Page 40: Section5 containment in unions and methods

Define classes and constructors

40

public interface IShape {}

public class CompositeShape implements IShape {private IShape top;private IShape bottom;public CompositeShape(IShape top, IShape bottom) {

this.top = top;this.bottom = bottom;

}}

public abstract class ASingleShape implements Ishape {protected CartPt location;public ASingleShape(CartPt location) {

this.location = location;}

}

Page 41: Section5 containment in unions and methods

Define classes and constructors

41

public class Dot extends ASingleShape {public Dot(CartPt location) {super(location);

}}

public class Circle extends ASingleShape {private int radius;public Circle(CartPt location, int radius) {super(location);this.radius = radius;

}}

public class Square extends ASingleShape {private int size;public Square(CartPt location, int size){super(location);this.size = size;

}}

Page 42: Section5 containment in unions and methods

Define classes and constructors

42

public class Rectangle extends ASingleShape {private int width;private int height;public Rectangle(CartPt location, int width, int height) {super(location);this.width = width;this.height = height;

}}

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

}}

Page 43: Section5 containment in unions and methods

Test Constructor

43

public class ShapeTest extends TestCase {public void testConstructor() {

IShape s1 = new Square(new CartPt(4, 3), 40);IShape s2 = new Square(new CartPt(3, 4), 50);IShape c1 = new Circle(new CartPt(0, 0), 20);IShape c2 = new Circle(new CartPt(12, 5), 20);

IShape u1 = new CompositeShape(s1, s2);IShape u2 = new CompositeShape(s1, c2);IShape u3 = new CompositeShape(c1, u1);IShape u4 = new CompositeShape(u3, u2);IShape u5 = new CompositeShape(s1,

new Compositeshape(c1, s2)); System.out.println(u5);

}}

Page 44: Section5 containment in unions and methods

River Systems Example

• The environmental protection agency monitors the water quality for river systems.

• A river system consists of a source of river, its tributaries (nhánh sông), the tributaries of the tributaries, and so on. Besides, each of part in the river system has location, and its length.

• The place where a tributary flows into a river is called confluence (hợp dòng).

• The initial river segment is its source (bắt nguồn)• The river's end - the segment that ends in a sea

or another river - is called its mouth (cửa sông)44

Page 45: Section5 containment in unions and methods

45

Source

Mouth

m(7, 5)

a(5, 5)

u(3, 7)

t(1, 5)s(1, 1)

b(3, 3)

Confluence

120 50

10060

30

Page 46: Section5 containment in unions and methods

Class diagram

46

Source

Mouth- Location location- ARiver river

Location- int x- int y- String name

Confluence- ARiver left- ARiver right

ARiver# Location location# double length

Page 47: Section5 containment in unions and methods

Define classes and constructors

47

public class Location {private int x;private int y;private String name;public Location(int x, int y, String name) {

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

}}

public class Mouth {private Location location;private ARiver river;public Mouth(Location location, ARiver river) {

this.location=location;this.river=river;

}}

Page 48: Section5 containment in unions and methods

48

public abstract class ARiver {protected Location location;protected double length;public ARiver(Location location, double length) {

this.location=location;this.length=length;

}}

public class Source extends ARiver {public Source(Location location, double length) {

super(location,length);}

}

public class Confluence extends ARiver {private ARiver left;private ARiver right;public Confluence(Location location, double length,

ARiver left, ARiver right) {super(location,length);this.left=left;this.right=right;

}}

Page 49: Section5 containment in unions and methods

Test Constructor

49

public class ARiverTest extends TestCase {public void testConstructor() {

ARiver s = new Source(new Location(1, 1, "s"),120.0);ARiver t = new Source(new Location(1, 5, "t"), 50.0);ARiver u = new Source(new Location(3, 7, "u"),100.0);

ARiver b = new Confluence(new Location(3, 3, "b"), 60.0, s, t);

ARiver a = new Confluence(new Location(5, 5, "a"), 30.0, b, u);

Mouth m = new Mouth(new Location(7, 5, "m"), a);}

}

m(7, 5)

a(5, 5)

u(3, 7)

t(1, 5)s(1, 1)

b(3, 3)

120 50

100

60

30

Page 50: Section5 containment in unions and methods

Exercises

• Part I : 5.1 to 5.5 (HTDCH)5.6 to 5.7 (HTDCH)

50

Page 51: Section5 containment in unions and methods

Exercises 5.3

• . . . Develop a program that assists real estate agents. The program deals with listings of available houses. . . – Make examples of listings. Develop a data definition

for listings of houses.– Implement the definitionwith classes. Translate the

examples into objects

51

Page 52: Section5 containment in unions and methods

Exercises 5.4

• Design a program that assists a bookstore manager with reading lists for local schools. . . – Develop a class diagramfor a list of books (by hand).

Translate the diagram into classes. – Create two lists of books that contain at least one of

the books in exercise 2.2 plus one or more of your favorite books

52

Page 53: Section5 containment in unions and methods

Exercises 5.6

. . . Develop a programthat helps with recording a person’s ancestor tree. Specifically, for each person we wish to remember the person’s name and year of birth, in addition to the ancestry on the father’s and the mother’s side, if it is available.

The tree on the left is an example; the nodes with “???” indicate where the genealogist couldn’t find any information.

• . . .Develop the class diagram (by hand) and the class definitions to represent ancestor family trees. Then translate the sample tree into an object.

• Also draw your family’s ancestor tree as far as known and represent it as an object.

53

Page 54: Section5 containment in unions and methods

• Exercise 5.7 Research the tributaries of your favorite river. Create a data representation of the river and its tributaries. Draw the river system as a schematic diagram.

• Exercise 5.8 Modify the classes that represent river segments,mouths, and sources so that you can add the names of these pieces to your data representation. Can you think of a river system that needs names for all three segments involved in a confluence? Represent such a confluence with the revised classes.

54

Page 55: Section5 containment in unions and methods

Methods and Classes with Mutual

References

55

Page 56: Section5 containment in unions and methods

Recall Inventory problem

56

MTInventory Toy- String name- double price- int available

ConsInventory- Toy first- Inventory rest

Inventory

Class diagram

Page 57: Section5 containment in unions and methods

Recall Inventory problem

• Develop the method contains, which determines whether or not the name of toy occurs in the Inventory

• Develop the method isBelow, which checks whether all of the prices of toys in inventory are below the threshold.

• Develop the method howMany, which produces the number of items in the list.

• Develop the method raisePrice, which produces an inventory in which all prices are raised by 5% (use mutable and immutable).

57

Page 58: Section5 containment in unions and methods

Add methods to the Inventory’s

Class Diagram

58

Q: Write Java method templates for all the classes in the class diagram ?

MTInventory

+ ??? nnn(???)

Toy- String name- double price- int available

+ ??? kkk(???)

ConsInventory- Toy first- Inventory rest

+ ??? nnn(???)

Inventory

+ ??? nnn(???)

Page 59: Section5 containment in unions and methods

Java template for Toy

59

public class Toy {private String name;private double price;private int available;public Toy(String name, double price, int available) {

this.name = name;this.price = price;this.available = available;

}

public ??? kkk(???) {...this.name......this.price......this.available...

}}

Page 60: Section5 containment in unions and methods

60

public interface Inventory {public ??? nnn(???);

}

Java template for MTInventorypublic class MTInventory implements Inventory {

public MTInventory () { }

public ??? nnn(???) {

...}

}

Java template for Inventory

Page 61: Section5 containment in unions and methods

Java template for ConsInventory

61

public class ConsInventoy implements Inventory {private Toy first;private Inventory rest;public Cons(Toy first, Inventory rest) {

this.first = first;this.rest = rest;

}

public ??? nnn(???) {...this.first.kkk(???)......this.rest.nnn(???)...

}}

Since all instances in the rest field are always created from either MTInventory or ConsInventory, this means that the method call ...this.rest.nnn() ... really invokes one of the concrete nnn methods in MTInventory or ConsInventory

Page 62: Section5 containment in unions and methods

Method manipulates on List’s

elements

62

Page 63: Section5 containment in unions and methods

Add contains method • Develop the method contains, which determines

whether or not the name of toy occurs in the Inventory

63

MTInventory

+ boolean contains(String name)

Toy

- String name

- double price

- int available

+ ??? kkk(???)

ConsInventory

- Toy first

- Inventory rest

+ boolean contains(String name)

Inventory

+ boolean contains(String name)

Page 64: Section5 containment in unions and methods

contains() for Inventory

64

public interface Inventory {// determines whether or not the name of// toy occurs in the Inventorypublic boolean contains(String toyName);

}

Page 65: Section5 containment in unions and methods

contains() for MTInventory and

ConsInventory

65

//in class MTInventorypublic boolean contains(String toyName) {

return false;}

//in class Toypublic boolean sameName(String toyName) {

return this.name.equals(toyName);}

// in class ConsInventorypublic boolean contains(String toyName) {

return this.first.sameName(toyName) || this.rest.contains(toyName);

}

Page 66: Section5 containment in unions and methods

Test contains()

66

public void testContains(){Toy doll = new Toy("doll", 17.95, 5);Toy robot = new Toy("robot", 22.05, 3);Toy gun = new Toy ("gun", 15.0, 4);

Inventory ivt = new ConsInventory(doll, new ConsInventory(robot, new ConsInventory(gun, new MTInventory())));

assertTrue(ivt.contains("doll"));

assertFalse(ivt.contains("car")); }

Page 67: Section5 containment in unions and methods

Class diagram after add contains()

67

Inventory

+boolean contain(String name)

MTInventory

+boolean contain(String name)

ConsInventory

-Toy first-Inventory rest

+boolean contain(String name)

Toy

-String name-double price-int available

+boolean sameName(String name)

Page 68: Section5 containment in unions and methods

More requirement

• Develop the method isBelow, which checks whether all of the prices of toys in inventory are below the threshold

68

Page 69: Section5 containment in unions and methods

Add isBelow method

69

Inventory

+boolean contain(String name)+boolean isBelow(double threshold)

MTInventory

+boolean contain(String name)+boolean isBelow(double threshold)

ConsInventory

-Toy first-Inventory rest

+boolean contain(String name)+boolean isBelow(double threshold)

Toy

-String name-double price-int available

+boolean sameName(String name)+??? kkk(???)

Page 70: Section5 containment in unions and methods

isBellow() for Inventory

70

public interface Inventory {

// determines whether or not all// prices of toys in the Inventory// bellow a thresholdpublic boolean isBellow(double threshold);

}

Page 71: Section5 containment in unions and methods

isBelow() for MTInventory and

ConsInventory

71

//inside of MTInventory class public boolean isBellow(double threshold) {

return true;}

// inside of ConsInventory class public boolean isBellow(double threshold) {

return this.first.isPriceBelow(threshold) && this.rest.isBellow(threshold);

}

// inside of Toy class public boolean isPriceBelow(double threshold) {

return this.price < threshold;}

Page 72: Section5 containment in unions and methods

Test isBelow()

72

public void testIsBellow(){Toy doll = new Toy("doll", 17.95, 5);Toy robot = new Toy("robot", 22.05, 3);Toy gun = new Toy ("gun", 15.0,4);

Inventory ivt = new ConsInventory(doll, new ConsInventory(robot, new ConsInventory(gun, new MTInventory())));

assertTrue(ivt.isBellow(23.0));

assertFalse(ivt.isBellow(20.0));}

Page 73: Section5 containment in unions and methods

Class diagram after add isBelow()

73

Inventory

+boolean contain(String name)+boolean isBelow(double threshold)

MTInventory

+boolean contain(String name)+boolean isBelow(double threshold)

ConsInventory

-Toy first-Inventory rest

+boolean contain(String name)+boolean isBelow(double threshold)

Toy

-String name-double price-int available

+boolean sameName(String name)+boolean isPriceBelow(double threshold)

Page 74: Section5 containment in unions and methods

More requirement

• Develop the method howMany, which produces the number of toy items in the inventory.

74

Inventory

+boolean contain(String name)+boolean isBelow(double threshold)+int howMany()

MTInventory

+boolean contain(String name)+boolean isBelow(double threshold)+int howMany()

ConsInventory

-Toy first-Inventory rest

+boolean contain(String name)+boolean isBelow(double threshold)+int howMany()

Toy

-String name-double price-int available

+boolean sameName(String name)+boolean isPriceBelow(double threshold)+??? kkk(???)

Page 75: Section5 containment in unions and methods

howMany() for Inventory

75

public interface Inventory {// count the number of items in the Inventorypublic int howMany();

}

Page 76: Section5 containment in unions and methods

howMany() for MTInventory and

ConsInventory

76

// inside of MTInventory class public int howMany() {

return 0;}

// inside of ConsInventory class public int howMany() {

return 1 + this.rest.howMany();}

Page 77: Section5 containment in unions and methods

Test howMany()

77

public void testHowMany() {Toy doll = new Toy("doll", 17.95, 5);Toy robot = new Toy("robot", 22.05, 3);Toy gun = new Toy ("gun", 15.0,4);

Inventory ivt = new ConsInventory(doll, new ConsInventory(robot, new ConsInventory(gun, new MTInventory())));

assertEquals(3, ivt.howMany()); }

Page 78: Section5 containment in unions and methods

New requiremqnt

• Develop the method raisePrice, which produces an inventory in which all prices are raised by 5% (use immutable).

78

Page 79: Section5 containment in unions and methods

Add raisePrice() method (Immutable)

79

Inventory

+boolean contain(String name)+boolean isBelow(double threshold)+int howMany()+Inventory raisePrice(double rate)

MTInventory

+boolean contain(String name)+boolean isBelow(double threshold)+int howMany()+Inventory raisePrice(double rate)

ConsInventory

-Toy first-Inventory rest

+boolean contain(String name)+boolean isBelow(double threshold)+int howMany()+Inventory raisePrice(double rate)

Toy

-String name-double price-int available

+boolean sameName(String name)+boolean isPriceBelow(double threshold)+??? kkk(???)

Page 80: Section5 containment in unions and methods

raisePrice() for Inventory -

Immutable version

• Q: what does the raisePrice method return?

• A: It returns a new Inventory whose each element has new price

80

public interface Inventory {// raise all prices of toys // in the Inventory with ratepublic Inventory raisePrice(double rate);

}

Page 81: Section5 containment in unions and methods

raisePrice() for MTInventory

and ConsInventory

81

// inside of MTInventory class public Inventory raisePrice(double rate) {

return new MTInventory();}

// inside of ConsInventory class public Inventory raisePrice(double rate) {

Toy aToy = this.first.copyWithRaisePrice(rate);return new ConsInventory(aToy, this.rest.raisePrice());

}

// inside of Toy class public Toy copyWithRaisePrice(double rate) {

return new Toy(this.name, this.price * (1 + rate), this.available);

}

Page 82: Section5 containment in unions and methods

Test raisePrice()

Q: Check the contain of i3 before and after invoking raisePrice (). 82

public void testRaisePrice(){Toy doll = new Toy("doll", 17.95, 5);Toy robot = new Toy("robot", 22.05, 3);Toy gun = new Toy ("gun", 15.0,4);

Inventory ivt = new ConsInventory(doll, new ConsInventory(robot, new ConsInventory(gun, new MTInventory())));

// before invoking raisePrice()System.out.println(ivt);

System.out.println(ivt.raisePrice(0.05)); // after invoking raisePrice()System.out.println(ivt);

}

Page 83: Section5 containment in unions and methods

Class diagram after add raisePricer()

83

Inventory

+boolean contain(String name)+boolean isBelow(double threshold)+int howMany()+Inventory raisePrice(double rate)

MTInventory

+boolean contain(String name)+boolean isBelow(double threshold)+int howMany()+Inventory raisePrice(double rate)

ConsInventory

-Toy first-Inventory rest

+boolean contain(String name)+boolean isBelow(double threshold)+int howMany()+Inventory raisePrice(double rate)

Toy

-String name-double price-int available

+boolean sameName(String name)+boolean isPriceBelow(double threshold)+Toy copyWithRaisePrice(double rate)

Page 84: Section5 containment in unions and methods

raisePrice() - mutable version

• Develop the method raisePrice, which consumes an inventory and produces an inventory in which all prices are raised by a rate (use mutable).

84

Page 85: Section5 containment in unions and methods

raisePrice() for Inventory

- mutable version

• Q: what does the raisePrice method return?

• A: It just updates Inventory whose each element has new price and return void.

85

public interface Inventory {// raise all prices of toys // in the Inventory with ratepublic void raisePriceMutable(double rate);

}

Page 86: Section5 containment in unions and methods

// inside of ConsInventory class public void raisePriceMutable(double rate) {

this.first.setNewPrice(rate);this.rest.raisePriceMutable(rate);

}

raisePrice() for MTInventory

and ConsInventory

86

// inside of MTInventory class public void raisePriceMutable(double rate) { }

Delegation to Toy object

public void setNewPrice(double rate) {this.price = this.price * (1 + rate);

}

setNewPrice() in Toy class

Page 87: Section5 containment in unions and methods

Test raisePrice()

87

public void testRaisePrice(){Toy doll = new Toy("doll", 17.95, 5);Toy robot = new Toy("robot", 22.05, 3);Toy gun = new Toy ("gun", 15.0,4);

Inventory ivt = new ConsInventory(doll, new ConsInventory(robot, new ConsInventory(gun, new MTInventory())));

// before invoking raisePriceMutable(rate)System.out.println(i3); i3.raisePriceMutable(0.05);// after invoking raisePriceMutable(rate)System.out.println(i3);

}

Q: Check the contain of i3 before and after invoking raisePrice(rate)Compare the contain of i3 when raisePrice() and raisePrice(rate)are invoked

Page 88: Section5 containment in unions and methods

Final class diagram

88

Inventory

+boolean contain(String name)+boolean isBelow(double threshold)+int howMany()+Inventory raisePrice(double rate)

MTInventory

+boolean contain(String name)+boolean isBelow(double threshold)+int howMany()+Inventory raisePrice(double rate)

ConsInventory

-Toy first-Inventory rest

+boolean contain(String name)+boolean isBelow(double threshold)+int howMany()+Inventory raisePrice(double rate)

Toy

-String name-double price-int available

+boolean sameName(String name)+boolean isPriceBelow(double threshold)+Toy copyWithRaisePrice(double rate)+void setNewPrice(double rate)

Page 89: Section5 containment in unions and methods

Review “Overiding” and “Overloading”

• All classes in Java extends Object class• Q: distinguish “overloading” and “overriding” ?• A:

– Method toString() in class Cons is called overridingmethod toString () in class Object. Method toString () in class Cons disables method toString() in class Object.

– Method raisePrice() and raisePrice(double )in class Cons have the same name but different parameter is called overloading. When we invoke overloading methods, the method with appropriate argument will do

89

Page 90: Section5 containment in unions and methods

Exercise

• Exercise 9.5.7 (HTDP) Define the method averagePrice. It computes the average price of toys in Inventory. The average is the total of all prices divided by the number of toys

• Exercise 10.1.6 (HTDP) Develop the method replaceName, which consumes a list of toy and replaces all occurrences of “robot” with “r2d2” and otherwise retains the toy descriptions in the same order.

90

Page 91: Section5 containment in unions and methods

Exercise

• Exercise 10.1.7 (HTDP) Develop the method eliminate. The method consumes a string, called toyOfName and produces a list of toys that contains all components of list with the exception of the toy whose name matches toyOfName.

• Exercise 10.2.4 (HTDP) A phone directory combines names with phone numbers. Develop a data definition for phone records and directories. Develop the methods: – whoseNumber, which determines the name that goes with some

given phone number and phone directory.– phoneNumber, which determines the phone number that goes

with some given name and phone directory

91

Page 92: Section5 containment in unions and methods

Relax &

…Do Exercises …

92

Page 93: Section5 containment in unions and methods

Recall the problem of tracking a

runner’s workouts

• Develop a program that manages a runner's training log. Every day the runner enters one entry concerning the day's run. ...For each entry, the program should compute how fast the runner ran (Exercise 3.1.4 & 3.1.5 in week 1). ...The runner may also wish to determine the total number of miles run

• Q: Draw a class diagram for a runner’s log

93

Page 94: Section5 containment in unions and methods

Class diagram for a runner’s log

94

MTLogDate

- int day- int month- int year

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

ILog

ConsLog-Entry first- ILog rest

Page 95: Section5 containment in unions and methods

Add methods to the runner’s log Class

Diagram

95

Q: Write Java method templates for all the classes in the class diagram ?

MTLog

+ ??? nnn(???)

Date

- int day- int month- int year

+ ??? kkk(???)

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

+ ??? mmm(???)

ILog

+ ??? nnn(???)

ConsLog- Entry first- ILog rest

+ ??? nnn(???)

Page 96: Section5 containment in unions and methods

96

public interface ILog {public ??? nnn(???);

}

public class MTLog implements ILog {public MTLog() { }

public ??? nnn(???) {...

}}

Java template for MTLog

Java template for ILog

Page 97: Section5 containment in unions and methods

Java template for ConsLog

97

public class ConsLog implements ILog {private Entry first;private ILog rest;

public ConsLog(Entry first, ILog rest) {this.first = first;this.rest = rest;

}

public ??? nnn(???) {... this.first.mmm(??) ...... this.rest.nnn(??) ...

}}

Page 98: Section5 containment in unions and methods

Java template for Entry

98

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 ??? mmm(???) {

... this.date.kkk(??) ...

... this.distance ...

... this.duration ...

... this.comment ...}

Page 99: Section5 containment in unions and methods

Java template for Date

99

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

public Date(int day, int month, int year) {this.day = day;this.month = month;this.year = year;

}

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

}}

Page 100: Section5 containment in unions and methods

Examples for a runner’s log

• Q: Give some examples for a runner’s log. How many examples are at least needed?

100

Entry e1 = new Entry(new Date(5, 5, 2005), 5.0, 25, "Good");Entry e2 = new Entry(new Date(6, 6, 2005), 3.0, 24, "Tired");Entry e3 = new Entry(new Date(23, 6, 2005), 26.0, 156, "Great");

ILog log = new ConsLog(e1, new ConsLog(e2, new ConsLog(e3, new MTLog())));

Page 101: Section5 containment in unions and methods

Compute the total number of miles run

• Using the method template for ILog, design a method to compute the total number of miles run

101

ILog

+double miles()

MTLog

+double miles()

ConsLog

-Entry first-ILog rest

+double miles()

Entry

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

+??? mmm(???)

Date

-int day-int month-int year

+??? kkk(???)

Page 102: Section5 containment in unions and methods

miles() for ILog

• Q: Develop some examples to test the miles() method

102

public interface ILog {// to compute the total number of miles// recorded in this logpublic double miles();

}

Page 103: Section5 containment in unions and methods

Examples to test miles()

103

Entry e1 = new Entry(new Date(5, 5, 2005), 5.0, 25, "Good");Entry e2 = new Entry(new Date(6, 6, 2005), 3.0, 24, "Tired");Entry e3 = new Entry(new Date(23, 6, 2005), 26.0, 156, "Great");

ILog l0 = new MTLog();ILog l1 = new ConsLog(e1, l0);ILog l2 = new ConsLog(e2, l1);ILog l3 = new ConsLog(e3, l2);

l0.miles() � should be 0.0l1.miles() � should be 5.0l2.miles() � should be 8.0l3.miles() � should be 34.0

Q: Implement miles() in MTLog and ConsLog

Page 104: Section5 containment in unions and methods

miles() in MTLog

104

public class MTLog implements ILog {public MTLog() { }

public double miles() {return 0.0;

}}

Page 105: Section5 containment in unions and methods

miles() in ConsLog

105

public class ConsLog implements ILog {private Entry first;private ILog rest;

public ConsLog(Entry first, ILog rest) {this.first = first;this.rest = rest;

}

public double miles() {return this.first.getDistance() +

this.rest.miles();}

}

Page 106: Section5 containment in unions and methods

getDistance() in Entry

106

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

...

public double getDistance() {return this.distance;

}}

Page 107: Section5 containment in unions and methods

Test miles() method

107

public void testMiles() {Entry e1 = new Entry(new Date(5, 5, 2005), 5.0, 25, "Good");Entry e2 = new Entry(new Date(6, 6, 2005), 3.0, 24, "Tired");Entry e3 = new Entry(new Date(23, 6, 2005), 26.0, 156, "Great");

ILog l0 = new MTLog();ILog l1 = new ConsLog(e1, l0);ILog l2 = new ConsLog(e2, l1);ILog l3 = new ConsLog(e3, l2);

asserEquals(l0.miles(), 0.0);asserEquals(l1.miles(), 5.0);asserEquals(l2.miles(), 8.0);asserEquals(l3.miles(), 34.0);

}

Page 108: Section5 containment in unions and methods

Extension of the runner’s log problem

... The runner wants to see his log for a specific month of his training season. ...

108

ILog

+double miles()+ILog getLogs(int month, int year)

MTLog

+double miles()+ILog getLogs(int month, int year)

ConsLog

-Entry first-ILog rest

+double miles()+ILog getLogs(int month, int year)

Entry

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

+double getDistance()+??? mmm(???)

Date

-int day-int month-int year

+??? kkk(???)

Page 109: Section5 containment in unions and methods

getLogs() for ILog

• Q: Develop some examples to test the getLogs() method

109

public interface ILog {// to compute the total number of miles// recorded in this logpublic double miles();

// to extract those entries in this log// for the given month and yearpublic ILog getLogs(int month, int year);

}

Page 110: Section5 containment in unions and methods

Examples to test getLogs()

110

Entry e1 = new Entry(new Date(5, 5, 2005), 5.0, 25, "Good");Entry e2 = new Entry(new Date(6, 6, 2005), 3.0, 24, "Tired");Entry e3 = new Entry(new Date(23, 6, 2005), 26.0, 156, "Great");

ILog l0 = new MTLog();ILog l1 = new ConsLog(e1, l0);ILog l2 = new ConsLog(e2, l1);ILog l3 = new ConsLog(e3, l2);

l0.getLogs(6, 2005) � should be new MTLog()l1.getLogs(6, 2005) � should be new MTLog()l2.getLogs(6, 2005) � should be new ConsLog(e2, new MTLog())l3.getLogs(6, 2005) � should be

new ConsLog(e3, new ConsLog(e2, new MTLog()))

Q: Implement getLogs() in MTLog and ConsLog

Page 111: Section5 containment in unions and methods

getLog() for MTLog

111

public class MTLog implements ILog {// ...

public ILog getLogs(int month, int year) {return new MTLog();

}}

Page 112: Section5 containment in unions and methods

getLog() for ConsLog

112

public class ConsLog implements ILog {private Entry first;private ILog rest;// ...

public ILog getLogs(int month, int year) {if (this.first.sameMonthInAYear(month, year))

return new ConsLog(this.first,this.rest.getLogs(month, year));

else

return this.rest.getLogs(month, year);}

}

Page 113: Section5 containment in unions and methods

sameMonthInAYear() in Entry

113

public class Entry {private Date date;private double distance;private int duration;private String comment;//...public double getDistance() {

return this.distance;}

// was this entry made in the given month and yearpublic boolean sameMonthInAYear(int month, int year) {return (this.date.sameMonthInAYear(month, year);

}}

Page 114: Section5 containment in unions and methods

sameMonthInAYear() in Date

114

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 boolean sameMonthInAYear(int month, int year) {return (this.month == month) &&

(this.year == year);}

}

Q: Review delegation ?

Page 115: Section5 containment in unions and methods

Test getLogs()

115

public void testGetLogs() {Entry e1 = new Entry(new Date(5, 5, 2005), 5.0, 25, "Good");Entry e2 = new Entry(new Date(6, 6, 2005), 3.0, 24, "Tired");Entry e3 = new Entry(new Date(23, 6, 2005), 26.0, 156, "Great");

ILog l0 = new MTLog();ILog l1 = new ConsLog(e1, l0);ILog l2 = new ConsLog(e2, l1);ILog l3 = new ConsLog(e3, l2);

assertTrue(l0.getLogs(6, 2005).equals(new MTLog()));assertTrue(l1.getLogs(6, 2005).equals(new MTLog()));assertTrue(l2.getLogs(6, 2005).equals(

new ConsLog(e2, new MTLog())));assertTrue(l3.getLogs(6, 2005).equals(

new ConsLog(e3, new ConsLog(e2, new MTLog()))));}

Page 116: Section5 containment in unions and methods

equals() method

116

// in MTLog classpublic boolean equals(Object obj) {

if (obj == null || !(obj instanceof MTLog)return false;

return true;}

// inside ConsLog classpublic boolean equals(Object obj) {

if (obj == null || !(obj instanceof ConsLog))return false;

else {ConsLog that = (ConsLog) obj;return this.first.equals(that.first)

&& this.rest.equals(that.rest);}

}

Page 117: Section5 containment in unions and methods

117

// in Entry classpublic boolean equals(Object obj) {

if (obj == null || !(obj instanceof Entry))return false;

else {Entry that = (Entry) obj;return this.date.equals(that.date) &&

this.distance == that.distance && this.durationInMinutes == that.durationInMinutes && this.postRunFeeling.equals(that.postRunFeeling);

}}

}// inside Date classpublic boolean equals(Object obj) {

if (obj == null || !(obj instanceof Date)) return false;

else {Date that = (Date) obj;return this.day == that.day &&

this.month == that.month && this.year == that.year;

}}

Page 118: Section5 containment in unions and methods

class diagram

118

ILog

+double miles()+ILog getLogs(int month, int year)

MTLog

+double miles()+ILog getLogs(int month, int year)

ConsLog

-Entry first-ILog rest

+double miles()+ILog getLogs(int month, int year)

Entry

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

+double getDistance()+boolean sameMonthInAYear(int month, int year)

Date

-int day-int month-int year

+boolean sameMonthInAYear(int month, int year)

Page 119: Section5 containment in unions and methods

Exercise 6.1.1

• Collect all the pieces of getLogs() and insert the method definitions in the class hierarchy for logs. Develop examples for sameMonthInAYear() and include them with the test suite. Draw the class diagram for this hierarchy

119

Page 120: Section5 containment in unions and methods

Exercise 6.1.2

• Suppose the requirements for the program that tracks a runner's log includes this request: ... The runner wants to know the total distance run in a given month...

Design the method that computes this number and add it to the class hierarchy of exercise 6.1.1.

120

Page 121: Section5 containment in unions and methods

Exercise 6.1.3

• Suppose the requirements for the program that tracks a runner's log includes this request:

... A runner wishes to know the maximum distance ever run ...

Design the method that computes this number and add it to the class hierarchy of exercise 6.1.1

Assume that the method produces 0 if the log is empty.

121

Page 122: Section5 containment in unions and methods

List Sorting

122

Page 123: Section5 containment in unions and methods

Problem Statement

...

The runner would like to see the log with entries ordered according to the distance covered in each run, from the shortest to the longest distance.

...

• Q: Which class should this operation belong to?

123

Page 124: Section5 containment in unions and methods

Modification of ILog

124

ILog

+ILog sortByDistance()

MTLog

+ILog sortByDistance()

ConsLog

-Entry first-ILog rest

+ILog sortByDistance()

Entry

-Date date-double distance-int duration

-String comment

Date

-int day

-int mont-int year

...

Page 125: Section5 containment in unions and methods

Examples

125

Entry e1 = new Entry(new Date(5, 5, 2005), 5.0, 25, "Good");Entry e2 = new Entry(new Date(6, 6, 2005), 3.0, 24, "Tired");Entry e3 = new Entry(new Date(23, 6, 2005), 26.0, 156, "Great");

ILog l0 = new MTLog();ILog l1 = new ConsLog(e1, l0);ILog l2 = new ConsLog(e2, l1);ILog l3 = new ConsLog(e3, l2);

l0.sortByDistance() � should be new MTLog()l1.sortByDistance() � should be new ConsLog(e1, new MTLog())

l2.sortByDistance()

� should be new ConsLog(e2, new ConsLog(e1, new MTLog()))

l3.sortByDistance()

� should be new ConsLog(e2, new ConsLog(e1, new ConsLog(e3, new MTLog()))

Page 126: Section5 containment in unions and methods

sortByDistance() in ILog

126

public interface ILog {// ...

// to create from this log a new log with// entries sorted by distancepublic ILog sortByDistance();

}

Page 127: Section5 containment in unions and methods

sortByDistance() in MTLog

127

public class MTLog implements ILog {public MTLog() { }// ...

public ILog sortByDistance() {return new MTLog();

}}

Page 128: Section5 containment in unions and methods

Template of sortByDistance() in

ConsLog

128

public class ConsLog implements ILog {private Entry first;private ILog rest;// ...

public ILog sortByDistance() {... this.first.mmm(??) ...... this.rest.sortByDistance() ...

}}

Page 129: Section5 containment in unions and methods

Solution of sortByDistance() in

ConsLog

• To sort a ConsLog, we need to insert the firstentry into the sorted version of rest to obtained the whole sorted log.

129

public class ConsLog implements ILog {private Entry first;private ILog rest;//...

public ILog sortByDistance() {return this.rest.sortByDistance()

.insertInDistanceOrder(this.first);}

}

Page 130: Section5 containment in unions and methods

Modification of ILog

130

ILog

+ILog sortByDistance()

+ILog insertInDistanceOrder(Entry e)

MTLog

+ILog sortByDistance()

+ILog insertInDistanceOrder(Entry e)

ConsLog

-Entry first

-ILog rest

+ILog sortByDistance()

+ILog insertInDistanceOrder(Entry e)

Entry

-Date date

-double distance

-int duration

-String comment

Date

-int day

-int mont

-int year

+ ...()

Page 131: Section5 containment in unions and methods

insertInDistanceOrder()

in ILog

131

public interface ILog {// ...// to create from this log a new log with// entries sorted by distance public ILog sortByDistance();

// insert the given entry into // this sorted logpublic ILog insertInDistanceOrder(Entry e);

}

Page 132: Section5 containment in unions and methods

Examples for insertInDistanceOrder()

132

Entry e1 = new Entry(new Date(5, 5, 2005), 5.0, 25, "Good");Entry e2 = new Entry(new Date(6, 6, 2005), 3.0, 24, "Tired");Entry e3 = new Entry(new Date(23, 6, 2005), 26.0, 156, "Great");Entry e4 = new Entry(new Date(15, 7, 2005), 10.0, 61, "Tierd");

ILog ls0 = new MTLog();ILog ls1 = ls0.insertInDistanceOrder(e1);// should be new new ConsLog(e1, new MTLog()))

ILog ls2 = ls1.insertInDistanceOrder(e2);// should be new ConsLog(e2, new ConsLog(e1, new MTLog()))

ILog ls3 = ls2.insertInDistanceOrder(e3);// should be new ConsLog(e2, new ConsLog(e1,

new ConsLog(e3, new MTLog())))

ILog ls4 = ls3.insertInDistanceOrder(e4);// should be new ConsLog(e2, new ConsLog(e1, new ConsLog(e4,

new ConsLog(e3, new MTLog())))

Page 133: Section5 containment in unions and methods

insertInDistanceOrder()

in MTLog

133

public class MTLog implements ILog {public MTLog() { }// ...

public ILog sortByDistance() {return this;

}

protected ILog insertInDistanceOrder(Entry e) {return new ConsLog(e, this);

}}

Page 134: Section5 containment in unions and methods

insertInDistanceOrder() in

ConsLog

134

public class ConsLog implements ILog {private Entry first;private ILog rest;

public ILog sortByDistance() {return this.rest.sortByDistance()

.insertInDistanceOrder(this.first);}

protected ILog insertInDistanceOrder(Entry e) {if (e.hasDistanceShorterThan(this.first))

return new ConsLog(e, this);else

return new ConsLog(this.first,this.rest.insertInDistanceOrder(e));

}}

Page 135: Section5 containment in unions and methods

hasDistanceShorterThan() in

Entry

135

public class Entry {private Date date;private double distance;private int duration;private String comment;// ...

public boolean hasDistanceShorterThan(Entry entry) {return this.distance < entry.distance;

}}

Page 136: Section5 containment in unions and methods

Exercise 6.2.1

Suppose the requirements for the program that tracks a runner’s log includes this request:

• ... The runner would like to see the log with entries ordered according to the pace computed in minutes per mile in each run, from the fastest to the slowest ...

• Design this sorting method. Hint: Don’t forget to design methods for auxiliary tasks.

136

Page 137: Section5 containment in unions and methods

Exercise (cont)

• Exercise 12.2.1 (HTDP). Develop a program that sorts lists of mail messages by date. Mail structures are defined as follows: from, date,message

137

Page 138: Section5 containment in unions and methods

Overlapping Shapes Example

138

Page 139: Section5 containment in unions and methods

Remind The Problem

• Develop a drawing program that deals with at least three kinds of shapes: dots, squares, and circles. ...In addition, the program should also deal with overlaying shapes on each other. In the following figure, for example, we have superimposed a circle on the right side of a square:

• We could now also superimpose(thêm vào) this compounded shape on another shape and so on.

139

Page 140: Section5 containment in unions and methods

Class Diagram

CartesianPoint

- int x- int y

+ int getX()+ int getY()+ double distanceToO()+ double distanceTo(CartesianPoint that)+ void translate(int dx, int dy)

Dot Square

- int size

Circle

- int radius

Rectangle

- int width- int height

ShapeUtils

<<static>> + boolean within(int left, int mid, int right)

uses uses

ASingleShape

# CartesianPoint location

# ASingleShape(CartesianPoint location)+ double distanceToO()+ double area()+ boolean contains(CartesianPoint point)+ Rectangle boundingBox()+ double perimeter()

11

CompositeShape

- AShape top- AShape bot tom

+ double dis tanceToO()

AShape

+ double distanceToO() 22

140

Page 141: Section5 containment in unions and methods

Problem1

• ... The user wishes to know how close a combination of shapes is to the origin ...

141

Page 142: Section5 containment in unions and methods

Modified Class Diagram

CartesianPoint

- int x- int y

+ int getX()+ int getY()+ double distanceToO()+ double distanceTo(CartesianPoint that)+ void translate(int dx, int dy)

Dot Square

- int size

Circle

- int radius

Rectangle

- int width- int height

ShapeUtils

<<static>> + boolean within(int left, int mid, int right)

uses uses

ASingleShape

# CartesianPoint location

# ASingleShape(CartesianPoint location)+ double distanceToO()+ double area()+ boolean contains(CartesianPoint point)+ Rectangle boundingBox()+ double perimeter()

11

CompositeShape

- AShape top- AShape bot tom

+ double dis tanceToO()

AShape

+ double distanceToO() 22

142

Page 143: Section5 containment in unions and methods

distanceToO() in CompositeShape

143

public class CompositeShape implements IShape {private IShape top;private IShape bottom;public CompositeShape(IShape top, IShape bottom) {

this.top = top;this.bottom = bottom;

}

public double distanceToO() {return Math.min(this.top.distanceToO(),

this.bottom.distanceToO());}

}

Page 144: Section5 containment in unions and methods

Problem 2

• ... Add a method that determines whether some point in the Cartesian space falls within the boundaries of some shape. ...

144

Page 145: Section5 containment in unions and methods

Modified Class Diagram

ASingleShape

CartesianPoint location

ASingleShape(CartesianPoint location)double distanceToO()double area()boolean contains(CartesianPoint point)opname()Rectangle boundingBox()double perimeter()

Dot Square

int size

Circle

int radius

Rectangle

int widthint height

ShapeUtils

<<s tat ic>> boolean within(int left, int mid, int right )

uses uses

CartesianPoint

int xint y

int getX()int getY()double distanceToO()double distanceTo(CartesianPoint that)void translate(int dx, int dy)

11

AShape

double distanceToO()boolean contains(CartesianPoint point)

CompositeShape

AShape topAShape bottom

double distanceToO()boolean contains(CartesianPoint point)

22

145

Page 146: Section5 containment in unions and methods

contains() in CompositeShape

146

public class CompositeShape implements IShape {private IShape top;private IShape bottom;public CompositeShape(IShape top, IShape bottom) {

this.top = top;this.bottom = bottom;

}

public boolean contains(CartPt point) {return this.top.contains(point)

|| this.bottom.contains(point);}

}

Page 147: Section5 containment in unions and methods

Problem 3

• ... A graphics program must compute the bounding box for a shape. ...

147

Page 148: Section5 containment in unions and methods

Bounding box for Composite shape

148

O X

Y

a

b

c

c

r

(x1, y1)

(x2, y2)

(x3, y3)

(x1+a, y1+b)

(x3+c, y3+c)

Page 149: Section5 containment in unions and methods

boundingBox() Examples

149

IShape s1 = new Square(new CartPt(4, 3), 40);

IShape s2 = new Square(new CartPt(3, 4), 50);

IShape c1 = new Circle(new CartPt(0, 0), 20);

IShape c2 = new Circle(new CartPt(12, 5), 20);

IShape u1 = new CompositeShape(s1, s2);

IShape u2 = new CompositeShape(s1, c2);

IShape u3 = new CompositeShape(c1, u1);

IShape u4 = new CompositeShape(u3, u2);

s1.boundingBox() should be new Rectangle(new CartPt(4, 3), 40, 40)

s2.boundingBox() should be new Rectangle(new CartPt(3, 4), 50, 50)

c1.boundingBox() should be new Rectangle(new CartPt(-20, -20), 40, 40)

c2.boundingBox() should be new Rectangle(new CartPt(-8, -15), 40, 40)

u1.boundingBox() should be new Rectangle(new CartPt(3, 3), 50, 51)

u2.boundingBox() should be new Rectangle(new CartPt(-8, -15), 52, 58)

u3.boundingBox() should be new Rectangle(new CartPt(-20, -2), 73, 74)

u4.boundingBox() should be new Rectangle(new CartPt(-20, -20, 73, 74)

Page 150: Section5 containment in unions and methods

boundingBox() in CompositeShape

150

public Rectangle boundingBox() {

Rectangle bbTop = this.top.boundingBox();

Rectangle bbBottom = this.bottom.boundingBox();

int x1 = Math.min(bbTop.location.getX(),

bbBottom.location.getX());

int y1 = Math.min(bbTop.location.getY(),

bbBottom.location.getY());

int x2 = Math.max(bbTop.location.getX() + bbTop.getWidth(),

bbBottom.location.getX() + bbBottom.getWidth());

int y2 = Math.max(bbTop.location.getY() + bbTop.getHeight(),

bbBottom.location.getY() + bbBottom.getHeight());

return new Rectangle(new CartPt(x1, y1),

x2 - x1, y2 - y1);

}

Page 151: Section5 containment in unions and methods

Exercises

151

Page 152: Section5 containment in unions and methods

Exercise 6.5.1

Design a data representation for shopping lists.

Start from the class of grocery items developed in exercise 5.1.2 part I. Add the following methods:

• howMany, which computes the number of items on the shopping list;

• brandList, which produces the list of all brand names; and

• highestPrice, which determines the highest unit price among all items in the shopping list.

152

Page 153: Section5 containment in unions and methods

ShopingList class diagram

153

AnItem

#String brandName#double weight#double price

IceCream

-String flavor-String package

Coffee

-String label

Juice

-String flavor-String package

IShoppingList

MTShoppingList ConsShoppingList

-AnItem first-AShoppingList rest

Page 154: Section5 containment in unions and methods

Exercise 6.5.1 Class Diagram

154

AnItem# String branchName# double weight# double price

+ double unitPrice()+ boolean lowerPrice(double amount)+ boolean cheaperThan(AnItem that)()

Ice Cream- String flavor- String package

Coffee- String label

Juice- String flavor- String package

Page 155: Section5 containment in unions and methods

Exercise 6.5.2

Develop a program for managing discount bookstores (see exercise 5.1.4 part I):

• design a representation for lists of books;

• write down (in English) three examples of book lists and their corresponding data representations;

• develop the method thisAuthor, which produces the list of books that this author has authored.

155

Page 156: Section5 containment in unions and methods

Exercise 6.5.2 Class Diagram

156

ABook# String title# String author# double price# int publicationYear

+ double salePrice()+ boolean cheaperThan(ABook that)+ boolean sameAuthor(ABook that)

Hardcover

+ double salePrice()

Sale

+ double salePrice()

Paperback

+ double salePrice()

Page 157: Section5 containment in unions and methods

River Systems Example

157

Page 158: Section5 containment in unions and methods

158

Source

Mouth

m(7, 5)

a(5, 5)

u(3, 7)

t(1, 5)s(1, 1)

b(3, 3)

Confluence

120 50

10060

30

Page 159: Section5 containment in unions and methods

Class diagram

159

Source

Mouth- Location location- ARiver river

Location- int x- int y- String name

Confluence- ARiver left- ARiver right

ARiver# Location location# double length

Page 160: Section5 containment in unions and methods

Problems

• Problem 1– The EPA must represent river systems and monitor them…

An EPA officer may wish to query a computer about the number of sources that feed a river system…

• Problem 2– ... An EPA officer may wish to find out whether some

location is a part of a river system, regardless of whether it is a source, a confluence, or the river mouth. ...

• Problem 3– ... An EPA officer may request the number of miles of a

river system, either starting from the river's mouth or any of its confluence points. ...

160

Page 161: Section5 containment in unions and methods

Exercise 6.5.3

Extend the following methods to classes that represent river systems with the following methods:

• maxlength, which computes the length of the longest river segment;

• confluences, which counts the number of confluences in the river system; and

• locations, which produces a list of all locations on this river -- the sources, the mouths, and the confluences.

161

Page 162: Section5 containment in unions and methods

Relax &

…Do Exercises …

162

Too much hard exercises now

Try again, never stop practicing!