Professional Documents
Culture Documents
Methods
The Drawing Program
• Phát triển một chương trình vẽ liên quan đến ít nhất ba loại
hình dạng: dấu chấm (Dot), hình vuông (Square)và hình tròn
(Circle).
• Các hình nằm trên một lưới Descartes có gốc ở phía tây bắc.
- Một dấu chấm nằm trong lưới và được vẽ dưới dạng một
đĩa nhỏ có kích thước cố định (3 pixel).
- Vị trí của hình vuông được xác định thông qua góc tây bắc
của nó trong lưới và kích thước của nó.
- Các thuộc tính cơ bản của một đường tròn là tâm và bán
kính của nó.
Class diagram Express the relationship
between these classes,
IShape is one of a Dot, a so that IShape as types of
IShape
Square, a Circle data
CartPt
- int x
- int y
IZooAnimal
IShape
CartPt
- int x
- int y
Requirements
1. Tính diện tích của một hình (shape)
2. Tính khoảng cách của một hình đến điểm gốc
3. Xác định xem một số điểm nằm bên trong hình
4. Tính toán hộp giới hạn của một hình
• Tất cả các phương thức này rõ ràng hoạt động với các hình
nói chung nhưng có thể phải tính toán các kết quả khác nhau
tùy thuộc vào hình cụ thể mà chúng được gọi.
- Ví dụ, một (Dot) không có diện tích thực sự; diện tích
của Hình vuông (Square) được tính khác với diện tích
của Hình tròn (Circle).
• Trong một ngôn ngữ hướng đối tượng, chúng ta có thể thể
hiện yêu cầu này với việc bổ sung một thiết kế phương thức
vào giao diện IShape
Add method for union of Shapes
IShape
??? nnn()
CartPt
- int x
- int y
??? kkk()
kkk() Method Template of CartPt
public class CartPt {
private int x;
private int y;
public CartPt(int x, int y) {
this.x = x;
this.y = y;
}
+ ??? area(???)
CartPt
- int x
- int y
Augmenting IShape area()
purpose and signature
// inside of Circle
public double area() {
return Math.PI * this.radius * this.radius;
}
// inside of Square
public double area() {
return this.size * this.size;
}
Unit Testing
public class ShapeTest extends TestCase {
public void testArea() {
assertEquals(new Dot(new CartPt(4, 3))
.area(), 0.0, 0.01);
assertEquals(new Square(new CartPt(4, 3), 30)
.area(), 900, 0.01);
assertEquals(new Circle(new CartPt(5, 5), 20)
.area(), 1256.64, 0.01);
Polymorphism
2. Computing the distance of a
shape to the origin
What is the distance between a shape and the origin?
0 X
Y
Add method to class diagram
IShape
+ double area()
+ ??? distanceToO(???)
CartPt
- int x
- int y
+ double distanceToO()
distanceToO() purpose and signature
// inside of Circle
public double distanceToO() {
return this.loc.distanceToO();
}
// inside of Square
public double distanceToO() {
return this.loc.distanceToO();
}
distanceToO method in CartPt
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);
}
}
Unit Test
public class ShapeTest extends TestCase {
...
CartPt
-int x
-int y
+double distanceToO()
+double distanceTo(CartPt that)
contains() purpose and signature
public interface IShape {
// compute area of AShape
public double area();
// inside of Circle
public boolean contains(CartPt point) {
return this.loc.distanceTo(point) <= this.radius;
}
distanceTo() in CartPt
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);
}
y size
y + size
// inside of Square
public boolean contains(CartPt point) {
int x = this.loc.getX();
int y = this.loc.getY();
return this.between(point.getX(), x, x + this.size)
&& this.between(point.getY(), y, y + this.size);
}
//-------------------------------------------------------
// inside of CartPt
public class CartPt {
private int x;
private int y;
public int getX() { return this.x; }
public int getY() { return this.y; }
}
Unit test
public class ShapeTest extends TestCase {
public void testContain() {
assertTrue(new Dot(new CartPt(100, 200))
.contains(new CartPt(100, 200)));
assertFalse(new Dot(new CartPt(100, 200))
.contains(new CartPt(80, 220)));
+area()
+double distanceToO()
+boolean contains(CartPt point)
CartPt
-int x
-int y
+double distanceToO()
+double distanceTo(CartPt that)
4. Computing the bounding box of a
shape
• Hộp giới hạn là gì?
Hộp giới hạn là hình vuông nhỏ nhất bao quanh hoàn toàn
hình dạng đã cho
- Hộp giới hạn cho Square là chính hình vuông đã cho.
- Đối với một Circle, hộp giới hạn cũng là một hình
vuông, chiều rộng và chiều cao của nó là 2 * bán kính và góc
tây bắc của nó cách tâm vòng tròn một bán kính theo cả hai
hướng.
- Hộp giới hạn cho một Dot là một hình vuông không có
viền. Các nhà toán học gọi ý tưởng này là một trường hợp đặc
biệt.
<<interface>>
Add method to IShape
CartPt
-int x
-int y
+double distanceToO()
+double distanceTo(CartPt that)
boundingBox
purpose and signature
public interface IShape {
// compute area of AShape
public double area();
}
Examples
new Dot(new CartPt(5, 5)).boundingBox()
// should be
new Square(new CartPt(5, 5), 0)
inside of Square
public Square boundingBox() {
return new Square(this.loc, this.size);
}
boundingBox method in Circle
inside of CartPt
// translate this point to deltaX, deltaY distance
public CartPt translate(int dX, int dY) {
return new CartPt(this.x + dX, this.y + dY);
}
Unit test
public class ShapeTest extends TestCase {
...
Diagram +area()
+double distanceToO()
+boolean contains(CartPt point)
+Square boundingBox()
CartPt
-int x
-int y
+double distanceToO()
+double distanceTo(CartPt that)
Abstract with Class
Common Data
Similarities in Classes
• Sự tương đồng giữa các lớp là phổ biến trong unions.
• Một số biến thường chứa các định nghĩa trường giống hệt
nhau. Ngoài các trường, các biến đôi khi cũng chia sẻ các
định nghĩa phương thức giống hệt nhau hoặc tương tự nhau.
• union đầu tiên của chúng ta là một đại diện của các shape
hình học đơn giản. Cả ba lớp đều triển khai IShape. Mỗi lớp
chứa một trường đã nhập CartPt chỉ định vị trí của hình.
• Ở đây, lớp đại diện cho hai điểm chung: CartPt field và
implements specification
Inheritance
• Nếu chúng ta biến Dot thành một phần mở rộng của
AShape, nó sẽ kế thừa trường CartPt và nghĩa vụ triển khai
IShape:
public class Dot public class public class Circle
extends AShape { Square
extends AShape extends AShape {
• Nói chung, cụm từ B{ mở rộng A nói rằng B kế thừa tất cả các
tính năng của A (trường, phương thức và nghĩa vụ thực hiện),
bao gồm những tính năng mà A được thừa hưởng.
- A là LỚP CHA và B là LỚP CON;
- Chúng ta cũng nói rằng B TÁI TẠO A hoặc B ĐƯỢC XUẤT
PHÁT từ A.
• Có xu hướng gán những điểm chung cho lớp cha và những
điểm khác biệt cho các lớp con.
Revised class diagram
<<interface>> <<interface>>
IShape IShape
AShape CartPt
Dot Square Circle
-CartPt loc -int x
-CartPt loc -CartPt loc -CartPt loc -int y
-int size -int radius
<<interface>>
IShape
+area()
+double distanceToO()
+boolean contains(CartPt point)
+Square boundingBox()
• Nhưng việc triển khai các phương thức như area() là khác
nhau đối với mỗi lớp con.
• Solution: Add abstract methods to the abstract AShape class
Abstract Method and Class
• Một phương thức trừu tượng giống như thiết kế một phương
thức trong một interface, trước từ khóa abstract.
• Một phương thức trừu tượng không phải định nghĩa phương
thức và chuyển nhiệm vụ cho các lớp con
• Việc tạo các thể hiện của lớp AShape cũng vô nghĩa, bởi vì:
- Tất cả các thể hiện của AShape đều là thể hiện của Dot,
Square, or Circle
- Và nó chưa triển khai tất cả các phương thức từ interface
của nó.
• Chúng ta làm cho toàn bộ lớp AShape trở nên trừu tượng.
Abstract Method and Class
It also makes no sense to create instances
public interface IShape { of the AShape class,
// compute area of AShape we make the entire class abstract
public double area();
Final
IShape
Shape +area()
+double distanceToO()
+boolean contains(CartPt point)
Union +Square boundingBox()
class
diagram AShape
CartPt
-int x
-CartPt loc -int y
+area()
+double distanceToO()
+double distanceToO()
+boolean contains(CartPt point) +double distanceTo(CartPt point)
+Square boundingBox() + void translate(int dx, int dy)
+ int getX()
+ int getY()
• Mức tiêu hao nhiên liệu đối với ô tô và xe buýt phụ thuộc vào
số lượng hành khách mà phương tiện vận chuyển; mức tiêu
thụ nhiên liệu của xe tải tăng theo tải trọng của nó (tính bằng
tấn)
Class Diagram
• All vehicles has a fuel tank of
some size (in gallons) and
average mile-per-gallon
consumption of fuel per IVehicle
vehicle.
• We define an abstract class
AVehicle that contains the
common fields of all vehicles: AVehicle
- double fuelTankVolume // in gallons
fuelTankVolumn and - double averageMilePerGallon
averageMilePerGallon.
• Người quản lý cần biết chi phí đổ xăng cho một chiếc xe
với bình xăng rỗng ở mức giá nhiên liệu hiện tại để khu học
có thể lập dự toán cho ngân sách xăng
b1.refuelCost(2.00)
// should be 120.0
c1.refuelCost(2.00)
// should be 30.0
t1.refuelCost(2.00)
// should be 240.0
Implementation of refuelCost()
Vì ba lớp con có cùng cách triển khai cho reFuelCost(), nên chúng ta có
thể chuyển phương thức này sang lớp cha. Điều này có nghĩa là giờ đây
refuelCost() trong lớp AVehicle sẽ không còn trừu tượng nữa.
AVehicle
- double fuelTankVolume // in gallons
- double averageMilePerGallon
b1.fuelConsumption()
// should be 8
c1.fuelConsumption()
// should be 22.5
t1.fuelConsumption()
// should be 5.85
fuelConsumption() implement
• Trong trường hợp này, cả ba phương thức đều khác biệt với
nhau và chúng phải được xác định cho từng loại phương tiện
cụ thể.
// inside Bus
public double fuelConsumption() {
return this.averageMilePerGallon
* (1 – 0.01*this.nPassengers);
}
// inside Car
public double fuelConsumption() {
return this.averageMilePerGallon
* (1 – 0.1*this.nPassengers);
}
// inside Truck
public double fuelConsumption() {
return this.averageMilePerGallon
* (1 – 0.05*this.loadInTons);
}
Improved Class Diagram
IVehicle
AVehicle
- double fuelTankVolume // in gallons
- double averageMilePerGallon
+ double refuelCost(double costPerGallon)
AVehicle
- double fuelTankVolume // in gallons
- double averageMilePerGallon
+ double refuelCost(double costPerGallon)
+ double fuelConsumption()
+ double howFar()
CartPt
AShape
- int x
# CartPt location - int y
# AShape(CartPt location)
+ int getX()
+ double distanceToO() 1 + int getY()
+ double area()
+ double distanceToO()
+ boolean contains(CartPt point)
+ double distanceTo(CartPt that)
+ Square boundingBox()
+ void translate(int dx, int dy)
ATaxiVehicle
# int idNum
# int passengers
# int pricePerMile
Limo Van
Cab
- int minRental - boolean access
Exercise 4.7 (cont)
Add the following methods to the appropriate classes in the
hierarchy:
• fare, which computes the fare for a vehicle, based on the
number of miles traveled, and using the following
formulas for different vehicles:
– passengers in a cab just pay flat fee per mile
– passengers in a limo must pay at least the minimum rental fee,
otherwise they pay by the mile
– passengers in a van pay $1.00 extra for each passenger
• lowerPrice, which determines whether the fare for a
given number of miles is lower than some amount;
• cheaperThan, which determines whether the fare in one
vehicle is lower than the fare in another vehicle for the
same number of miles.
Exercise 4.8
• Develop a program that assists a bookstore manager in a discount bookstore.
The program should keep a record for each book. The record must include its
title, the author's name, its price, and its publication year. In addition, the
books There are three kinds of books with different pricing policy. The
hardcover books are sold at 20% off. The sale books are sold at 50% off. The
paperbacks are sold at the list price. Here are your tasks:
• Develop a class hierarchy for representing books in the discount bookstore.
• Develop the following methods:
– salePrice, which computes the sale price of each book;
– cheaperThan, which determines whether a book is cheaper than another
book;
– sameAuthor, which determines whether a book was written by some
given author which wrote another book.