1. Trang chủ
  2. » Giáo Dục - Đào Tạo

Methods and containment arrows (lập TRÌNH cơ bản SLIDE)

116 50 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 116
Dung lượng 448,54 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Define Class, Constructor and test Constructorpublic class GPSLocation { private double latitude /* degrees */; private double longitude /* degrees */; public GPSLocationdouble latitude

Trang 1

Methods and Containment

Arrows

Week 4,5,6

Basic Programming Course

Trang 2

Date example

• Develop a program that helps you keep track

of daily One date is described with three

pieces of information: a day , a month , and a

Class

Trang 3

Define Class, Constructor and test Constructor

public class Date {

private int day;

private int month;

private int year;

public Date(int day, int month, int year) {

public class TestDate extends TestCase {

public void testConstrutor(){

new Date(5, 6, 2003); // denotes June 5, 2003

new Date(6, 6, 2003); // denotes June 6, 2003

new Date(23, 6, 2000); // denotes June 23, 2000

}

Trang 4

GPS Location example

• Develop a GPS navigation program for cars

The physical GPS unit feeds the program with the current location Each such location

consists of two pieces of information: the

latitude and the longitude

GPSLocation

- double latitude

- double longitude Property or field

Method Data type

Class

Trang 5

Define Class, Constructor and test Constructor

public class GPSLocation {

private double latitude /* degrees */;

private double longitude /* degrees */;

public GPSLocation(double latitude, double longitude) {

public class TestGPSLocation extends TestCase {

public void testConstrutor(){

new GPSLocation (33.5, 86.8);

new GPSLocation (40.2, 72.4);

new GPSLocation (49.0, 110.3);

}

Trang 6

Class

A class is a generic description of a “thing” It has:

1 Attribute: describes the “thing”

Attributes = Properties = Information = Fields = Data =

Variables

2 Behavior: describes what the “thing” does

Behaviors = Methods = Functions = Operations

3 State: describes the state that “thing” belongs to

A “thing” in a computer system ‘come alive – they

have behavior

Trang 7

Car example

With a Car

• Attributes which we concern: manufacturer, color, speed,…

• Behaviors can happen with a car: how to start

up, how to speed up,

• States:

state,

Trang 8

Book example

A Book in library has:

• Attributes that we concern : name, author, publisher, price,…

• Behaviors can modeled with this book: borrow, payback,…

• States:

– If it is ready to be borrow, it in ready state

– if it is borrowed, it becomes busy state

– when it is old, damaged and taken stock of, it is in out of stock (thanh lý) state.

– …

Trang 9

Room example

A Room in hotel has:

• Attributes we concern: name, kind (may be: usual, deluxe, VIP,…), price per day,…

• Behavior can happen with a room: rent,…

– If it is ready to be rent, it is in ready state

– if it is rent, it becomes busy state

state

– …

Trang 10

Point example

A point in monitor has:

which tells us where the pixel is located in the

• Behaivors:

– Computes how far some pixel is from the origin

– Computes the distance between 2 pixels,…

• State: ?

So, some real-life objects do not have state.

Trang 11

– Compute his average score.

– Check whether the student is supervised by some teacher,

– Transfer this student for another head teacher.

• State: ?

Trang 12

Rectangle example

With a Rectangle:

• Attributes that we concern: height, width,

north west point,…

Trang 13

– The book Nhat ky Dang Thuy Tram, author is Dang Thuy Tram,

published by Tuoi Tre, price 3$ is an instance of Book class.

– The deluxe room- No 201, price 50 $ per day is an instance of Room

class.

– A red point (2,3) is an instance of Point class.

– The student Nguyen Van A, his head teacher is Miss Thuy, has 8 in

Math, 9 in Physic and 7 in Chemistry is is an instance of Student class – A rectangle has height 5 cm, width 3 cm, north west point (2,3) is an

Trang 14

• None modifier: Classes in the same package

can access this attribute / method.

• public : Classes in all packages can access this

attribute / method.

• private : Only the class itself can access this

attribute / method.

The public or private modifiers

for attribute and method

Encapsulation

Trang 15

Group discussion

•Find more class examples in real life?

•Find more class examples in real life which

do not have behavior, then add their

behavior?

•Distinguish class and instance of class

(object).

Trang 16

Relax &

… Do Exercises …

Trang 17

Entry example

• 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

Trang 18

Define class and constructor

(define-struct Date (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 class Entry { private Date date;

private double distance;

private int durationInMinutes;

private String postRunFeeling;

public Entry(Date date, double distance, int durationInMinutes,String postRunFeeling ) { this.date=date;

this.distance=distance;

this.durationInMinutes=durationInMinutes; this.postRunFeeling=postRunFeeling;

} }

Trang 19

Date date1 = new Date(6, 6, 2004);

Date date2 = new Date(23, 6, 2004);

} } package entry;

Date date1 = new Date(6, 6, 2004);

new Entry(date1, 2.8, 24, "tired");

Trang 21

ran in minutes per mile .Develop a method that computes the pace for a daily entry.

Trang 22

Solution 3.1.4: pace()

• Method implementation

public double pace() {

return this.durationInMinutes / this.distance;

}

• Unit testing

public void testPace() {

Entry entry = new Entry(new Date(5, 6, 2004), 5.3, 27, "good");

Trang 23

Exercise 3.1.5

• A runner's log refers to Dates (see the figure) 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

Trang 24

Method Implementation

public class Date {

private int day;

private int month;

private int year;

public Date(int day, int month, int year) { … }

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;

}

}

Trang 25

Unit Testing

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);

Trang 26

Exercise 3.1.5

• Develop a method that determines whether one entry occurs earlier than another entry.

Trang 27

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

method in ?

• A: : Put ealierThan() in both classes

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

Trang 28

public vois testEalierThan(){

Entry e1= new Entry(new Date(5, 6, 2004), 5.3, 27, "good");

Date date1 = new Date(6, 6, 2004);

Entry e2 = new Entry(date1, 2.8, 24, "tired");

Date date2 = new Date(23, 6, 2004);

Entry e3 = new Entry(date2, 26.2, 159, "exhausted");

assertTrue(e1.ealierThan(e2));

assertFalse( e1.ealierThan(e1));

assertFalse(e3.ealierThan(e2));

}

Trang 29

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)

Trang 30

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

??? ealierThan(???)

Trang 31

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

Trang 32

avenue

S tr

ee t

Trang 34

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

Trang 35

new Intersection(3, 3).closeTo(new Intersection(3, 2))

// should produce ? true

new Intersection(3, 3).closeTo(new Intersection(3, 5))

// should produce false

new Intersection(3,3).closeTo(new Intersection(5, 4))

// should produce false

• Q: Create a template and then implement the method

closeTo() in the Intersection class

Trang 36

Template

public class Intersection {

private int avenue;

private int street;

public Intersection(int avenue, int street) {

Trang 37

Method Implementation

public class Intersection {

private int avenue;

private int street;

public Intersection(int avenue, int street) {

this.avenue = avenue;

this.street = street;

}

public boolean closeTo(Intersection that ) {

return ((Math.abs(this.avenue - that avenue) <=1) &&

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

}

}

Trang 38

• Q: Create examples for the method closeTo()

in the Restaurant class

Trang 40

Template

public class Restaurant {

private String name;

private String food;

private String priceRange;

private Intersection intersection;

public Restaurant(String name, String food, String priceRange,

Trang 41

public class Restaurant {

private String name;

private String food;

private String priceRange;

private Intersection intersection;

public Restaurant(String name, String food, String priceRange,

Trang 42

Unit Testing

public void testCloseTo() {

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

Trang 43

Part I: Exercise 3.1.1 to 3.1.3 (HTDCH)

Trang 44

• Develop a program that can assist Amtrak customers 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?

Extended Exercises

(Lab hours)

Trang 45

Prepare for next week

How to design class hierarchy

• III Fun Methods       

 4 Methods and Containment Arrow   

Trang 46

Relax &

… Do Exercises …

Trang 47

The rectangles are located on the Cartesian plane

of a computer canvas, which has its origin in the northwest corner

Trang 48

determine the shortest distance of the

Rectangle to the origin.

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

       

Trang 49

northwest corner

Trang 50

Problem Analysis

We need two methods:

1 Measuring the distance of a Rectangle to the

Trang 51

A: Put distanceTo0 () in both classes.

The distanceTo0 () method deals with properties of the CartesianPoint

so that we delegate this computational task to the corresponding

methods in CartesianPoint class

Trang 52

• Q: Create a template and then implement the method

distanceToO() in the CartesianPoint class

Trang 54

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.

Trang 55

• Q: Create examples for the method

distanceToO() in the Rectangle class

Trang 56

Examples

CartesianPoint p = new CartesianPoint(3,4);

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

• Q: Create a template and then implement the method

distanceToO() in the Rectangle class

Trang 57

public class Rectangle {

private CartesianPoint northWestCorner;

private int width;

private int height;

public Rectangle(CartesianPoint northWestCorner, int width, int height) {

this.northWestCorner = northWestCorner;

this.width = width;

this.height = height;

}

public double distanceToO () {

this.northWestCorner.distanceToO()

this.width

this.height

}

Trang 58

Method Implementation

public class Rectangle {

private CartesianPoint northWestCorner;

private int width;

private int height;

public Rectangle(CartesianPoint northWestCorner, int width, int height) {

this.northWestCorner = northWestCorner;

this.width = width;

this.height = height;

}

public double distanceToO() {

return this.northWestCorner.distanceToO();

}

}

Trang 59

Unit Testing

public void testDistanceToO() {

CartesianPoint p = new CartesianPoint(3,4);

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

Trang 60

Problem Extension Statement

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

       

Trang 62

Solution 1

public class Rectangle {

private CartesianPoint northWestCorner;

private int width;

private int height;

public Rectangle(CartesianPoint northWestCorner, int width, int height) {

this.northWestCorner = northWestCorner;

this.width = width;

this.height = height;

}

public double distanceToO() {

return this.northWestCorner.distanceToO();

}

public double distanceFromCenterToO() {

double a = this.northWestCorner.getX() + this.width/2;

double b = this.northWestCorner.getY() + this.height/2;

Trang 63

public class CartesianPoint {

public double distanceToO() {

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

Trang 64

Solution 2

public class Rectangle {

private CartesianPoint northWestCorner;

private int width;

private int height;

public Rectangle(CartesianPoint northWestCorner, int width, int height) {

this.northWestCorner = northWestCorner;

this.width = width;

this.height = height;

}

public double distanceToO() {

returnthis.northWestCorner.distanceToO();

}

public double distanceFromCenterToO() {

returnthis.center.distanceToO();

}

}

• Q: How to find the value of the center?

Trang 65

Solution 2 (cont)

public class Rectangle {

private CartesianPoint northWestCorner;

private int width;

private int height;

public Rectangle(CartesianPoint northWestCorner, int width, int height) {

this.northWestCorner = northWestCorner;

this.width = width;

this.height = height;

}

public double distanceToO() {

return this.northWestCorner.distanceToO();

}

public CartesianPoint calculateCenter() {

double a = this.northWestCorner.getX() + this.width/2;

double b = this.northWestCorner.getY() + this.height/2;

return new CartesianPoint( (int)(a),(int)(b));

}

public double distanceFromCenterToO() {

Trang 66

+ int getY()

1

Trang 67

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 (disk)

• Computes the area of a ring, which is this disk with a hole

Ngày đăng: 29/03/2021, 10:41

w