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

Mutable immutable (lập TRÌNH cơ bản SLIDE)

59 28 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 59
Dung lượng 307,05 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 Define classpublic class Star { private String firstName; private String lastName; private String instrument; private int sales; private String lastName; private String

Trang 2

Date example

Class

Trang 3

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

program with the current location Each such location consists of two pieces of information: the latitude and the longitude

Trang 5

Define Class, Constructor and test Constructor

class GPSLocation {

double latitude /* degrees */;

double longitude /* degrees */;

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

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

Attributes = Properties = Information = Fields = Data = Variables

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

– when a car in good shape, it is in use state,

– When it is damaged, it becomes not workable 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

– when it is damaged, it is in-correct (sửa chữa) state

Trang 10

Point example

A point in monitor has:

• Attributes: x coordinate , which tells us where the pixel is in the horizontal direction, and y

coordinate , which tells us where the pixel is located in the downwards vertical direction and color

• 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 13

Object

An object is an instance of a class

• Example:

– The Land Cruiser, red color and speed is 300 km/h is an instance of Car class.

– The For Escape, white color and speed is 250 km/h is an instance of Car class.

– The book Harry Porter, author is Rowling J.K, is published by Amazon, price 20$ is an instance of Book class.

– 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 instance of Rectangle class.

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

Star example

name , instrument he uses and his sales

Trang 17

Property or field

MethodData type

Class

Trang 18

Define Class

Define classpublic class Star { private String firstName;

private String lastName;

private String instrument;

private int sales;

private String lastName;

private String instrument;

private int sales;

public Star(String firstName, String lastName, String instrument, int sales) { this.firstName = firstName;

Trang 19

new Star ("Abba", "John", "vocals", 12200);

Star aStar1 = new Star ("Elton", "John", "guitar", 20000);

Star aStar2 = new Star ("Debie", "Gission", "organ", 15000);

} }

Trang 20

private String firstName;

private String lastName;

private String instrument;

private int sales;

public Star(String firstName, String lastName, String instrument, int sales) { this.firstName = firstName;

this.lastName = lastName;

this.instrument = instrument;

this.sales = sales;

} public ??? incrementSales(???){

…this.firstName … …this.lastName … …this.instrument

…this.sales…

Trang 21

private String firstName;

private String lastName;

private String instrument;

private int sales;

public Star(String firstName, String lastName, String instrument, int sales) { this.firstName = firstName;

this.lastName = lastName;

this.instrument = instrument;

this.sales = sales;

} public Star incrementSales(int sales){

return new Star(this.firstName, this.lastName, this.instrument, sales); }

}Immutable

Trang 22

assertTrue(new Star ("Abba", "John", "vocals", 12200).incrementSales(20000) equals(new Star ("Abba", "John", "vocals",32200)));

Star aStar1 = new Star ("Elton", "John", "guitar", 20000);

Star aStar2 = new Star ("Debie", "Gission", "organ", 15000);

assertTrue(aStar1.incrementSales(30000).equals(new Star ("Elton", "John", "guitar", 50000)));

assertTrueaStar2.incrementSales(20000).equals(new Star ("Debie", "Gission", "organ", 15000)));

}

}

Test incrementSales function

(define aStar1 (make-Star "Elton" "John" "Guitar" 20000))

(define aStar2 (make-Star "Debie" "Gission" "organ"

Trang 23

Discuss more: equals method

• Q: Why we do not use Java built-in equals method?

• Our equals method:

public class Star {

private String firstName;

private String lastName;

private String instrument;

private int sales;

public boolean equals(Object obj){

if (null == obj || ! (obj instanceof Star))

Trang 24

mutableIncrementSales body

incrementSales methodpublic class Star {

private String firstName;

private String lastName;

private String instrument;

private int sales;

public Star(String firstName, String lastName, String instrument, int sales) { this.firstName = firstName;

this.lastName = lastName;

this.instrument = instrument;

this.sales = sales;

} public void setSales(int sales){

this.sales = sales ; }

}Mutable

Setter

Trang 25

Discuss more: getSales method

Q: Do we use “selector” this.sales outside Star class

A: No

Solution: getSales method

public class Star {

private String firstName;

private String lastName;

private String instrument;

private int sales;

public Star(String firstName, String lastName, String instrument, int sales) {

Trang 26

public void testMutableIncrementSales (){

Star aStar1 = new Star ("Elton", "John", "guitar", 20000);

Star aStar2 = new Star ("Debie", "Gission", "organ", 15000);

Trang 27

+ int getSales()

Property or field

MethodData type

Class

Trang 28

Exercise 2.3.3 (HTDP)

ticket, for example $5 Every performance costs the theater some money, for example $20 and plus service charge per attendee, for example $.50 Develop

produces how much income the attendees profit

Solution

Trang 29

Exercise 3.3.5 (HTDP)

which computes the height that a rocket reaches in a given amount of time If

the rocket accelerates at a constant rate g, it reaches a speed of g · t in t time units and a height of 1/2 * v * t where v is the speed at t   

Solution

Trang 30

Re l a x…

& D o E x e rcise

Trang 31

Student example

teacher.

teacher's name is equal to aTeacher and “none” otherwise.

Trang 32

Class diagram

Student

+ String id + String firstName + String lastName + String teacher

+ ??? check(???) + ??? transfer(???)

Property or field

MethodData type

Class

Trang 33

Define Class

Define classpublic class Student { private String id;

private String firstName;

private String lastName;

private String teacher;

}

Define structure

( (define-struct Student (id first last teacher))

Constructorpublic class Student { private String id;

private String firstName;

private String lastName;

private String teacher;

public Student(String id, String firstName, String l astName, String teacher) { this.id = id;

(make-Student

Trang 34

Test Student Constructor

(define aStudent1 (make-student “st2”

“Wilson” “Fillip” “Harper”)

(define aStudent2 (make-student “st3”

“Woops” “Helen” “Flatt”)

Trang 35

private String firstName;

private String lastName;

private String teacher;

public Student(String id, String firstName, String lastName, String teacher) { this.id = id;

}

Trang 36

private String firstName;

private String lastName;

private String teacher;

public Student(String id, String firstName, String lastName, String teacher) { this.id = id;

this.firstName = firstName;

this.lastName = lastName;

this.teacher = teacher;

} public void transfer(String thatTeacher){

this.teacher = thatTeacher;

}

public String check(String thatTeacher){

if (this.teacher.equals(thatTeacher)) return this.lastName;

return "none";

Trang 37

public void testCheck(){

assertEquals (new Student( "st1", "Find", "Matthew", "Fritz").check("Elise"),"none");

Student aStudent1 = new Student("st2", "Wilson", "Fillip", "Harper");

Student aStudent2 = new Student("st3", "Woops", "Helen", "Flatt");

assertEquals("none“, aStudent1.check("Lee"));

assertEquals("Helen“,aStudent2.check("Flatt"));

}

}

Test check function

(define aStudent1 (make-student “st2” “Wilson” “Fillip”

“Harper”)

(define aStudent2 (make-student “st3” “Woops” “Helen”

“Flatt”)

(string=? “none” (check (make-student “st1” “Find”

“Matthew” “Fritz”) “Elise”))

(string=? “none” (check aStudent1 “Lee”))

(string=? “Hellen” (check aStudent2 “Flatt”))

Trang 39

private String firstName;

private String lastName;

private String teacher;

public Student(String id, String firstName, String lastName, String teacher) { this.id = id;

}

}

Trang 40

private String firstName;

private String lastName;

private String teacher;

public Student(String id, String firstName, String lastName, String teacher) { this.id = id;

this.firstName = firstName;

this.lastName = lastName;

this.teacher = teacher;

}

public Student transfer(String thatTeacher){

return new Student (this.id, this.firstName, this.lastName,thatTeacher);

}

Immutable

Trang 41

public void testTransfer(){

assertTrue(new Student( "st1", "Find", "Matthew", "Fritz").tranfer("Elise") equals (new Student( "st1", "Find", "Matthew","Elise")));

Student aStudent1 = new Student("st2", "Wilson", "Fillip", "Harper");

Student aStudent2 = new Student("st3", "Woops", "Helen", "Flatt");

assertTrue(aStudent1.tranfer("Lee").equals (new Student("st2", "Wilson",

Test transfer function

(define aStudent1 (make-student “st2” “Wilson” “Fillip”

(transfer aStudent1 “Lee” )

(transfer aStudent2 “Flister” )

Trang 42

Discuss more: equals method

• Q: Why we do not use JUnit built-in equals method?

• Our equals method:

public class Student {

private String id;

private String firstName;

private String lastName;

private String teacher;

public Student(String id, String firstName, String lastName, String teacher) {

public boolean equals(Object obj){

if (null == obj || ! (obj instanceof Student))

Trang 43

transferMutable body

transfer methodpublic class Student { private String id;

private String firstName;

private String lastName;

private String teacher;

public Student(String id, String firstName, String lastName, String teacher) { this.id = id;

Trang 44

Discuss more: getTeacher method

Q: Do we use “selector” this.teacher outside Student class

A: No

Solution: getTeacher method

public class Student {

private String id;

private String firstName;

private String lastName;

private String teacher;

public Student(String id, String firstName, String lastName, String teacher) {

Trang 45

public void testMutableTransfer(){

Student aStudent1 = new Student("st2", "Wilson", "Fillip", "Harper");

Student aStudent2 = new Student("st3", "Woops", "Helen", "Flatt");

Trang 46

Class diagram

Student + String id

+ String firstName + String lastName + String teacher

+ String check(String thatTeacher) + Student transfer(String thatTeacher) + void mutableTransfer(String thatTeacher) + boolean equals(Student that)

+ String getTeacher()

Property or field

MethodData type

Class

Trang 47

Exercise 5.1.4 (HTDP)

quadratic equation It then determines whether the equation is degenerate and,

if not, how many solutions the equation has The function produces one of four

symbols: 'degenerate, 'two, 'one, or 'none.

Solution

Trang 48

Exercise 4.4.1 and 4.4.3 (HTDP)

• Information about the transaction in bank includes customer name, and deposit amount and maturity(computed in year)

• Develop the function interest It consumes a deposit amount and produces the actual amount of interest that the money earns

in a year The bank pays a flat 4% for deposits of up to $1,000, a flat 4.5% per year for deposits of up to $5,000, and a flat 5% for deposits of more than $5,000

• Some credit card companies pay back a small portion of the charges a customer makes over a year One company returns 25% for the first $500 of charges,

.50% for the next $1000 (that is, the portion between $500 and $1500),

75% for the next $1000 (that is, the portion between $1500 and $2500), and

1.0% for everything above $2500

Define the function payback , which consumes a charge amount and computes the corresponding pay-back amount.

SolutionSolution

Trang 49

Prepare for next week

How to design class hierarchy

I The Varieties of Data   

III Fun Methods       

Trang 50

Re l a x…

& D o E x e rcise

Trang 51

Solution 2.3.3 (HTDP)

• Class definition

public class MovieTheatre {

private double ticketPrice;

private double costForPerformance;

private double costPerAttendee;

public MovieTheatre(double ticketPrice, double costForPerformance, double costPerAttendee) {

this.ticketPrice = ticketPrice;

this.costForPerformance = costForPerformance;

this.costPerAttendee = costPerAttendee;

}

public double cost(int numAttendee){

return this.costForPerformance + this.costPerAttendee * numAttendee;

}

public double revenue(int numAttendee){

return this.ticketPrice * numAttendee;

}

public double totalProfit(int numAttendee){

return this.revenue(numAttendee)- this.cost(numAttendee);

}

}

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

TỪ KHÓA LIÊN QUAN

w