Section2 methods for classes

66
Methods for classes 7/16/2014 1

Transcript of Section2 methods for classes

Methods for classes

7/16/2014 1

The public or private modifiersfor attribute and method

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

7/16/2014 2

Encapsulation

Review: Design Class Method Steps

1. Problem analysis and data definitions – Specify pieces of information the method needs and output

infomation

2. Purpose and contract (method signature)– The purpose statement is just a comment that describes

the method's task in general terms. – The method signature is a specification of inputs and

outputs, or contract as we used to call it.

7/16/2014 3

Design Class Method Steps

3. Examples – the creation of examples that illustrate the purpose

statement in a concrete manner

4. Template – lists all parts of data available for the computation inside of

the body of the method

5. Method definition– Implement method

6. Tests– to turn the examples into executable tests

7/16/2014 4

Star example

• Suppose we wish to represent a star information which has first name, last name, instrument he uses and his sales.

• Design methods:– Check whether one star is same another star.– Check whether one star's sales is greater than another

star's sales.– Adds 20.000 to the star's sales.

7/16/2014 5

Class Diagram

7/16/2014

Data type

Class

Property or field

Method

Star- String firstName- String lastName- String instrument- int sales

+ ???isSame(???)+ ???isBiggerSales (???)+ ???incrementSales(???)

6

Define Class and Constructor

7/16/2014

public class Star {private String firstName;private String lastName;private String instrument;private int sales;

// contructorpublic Star(String firstName, String lastName,

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

}}

7

Test Star Constructor

7/16/2014

import junit.framework.*;

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

new Star("Abba", "John", "vocals", 12200);Star aStar1 = new Star("Elton", "John", "guitar", 20000);Star aStar2 = new Star("Debie", "Gission", "organ", 15000);

}}

8

Compare equals of 2 objectsCheck whether one star is same another star

• isSame method template

7/16/2014

public class Star {private String firstName;private String lastName;private String instrument;private int sales;...// check whhether this star is same another starpublic boolean isSame(Star other) {

...this.firstName...this.lastName...

...this.instrument...this.sales...

...other.firstName...other.lastName...

...other.instrument...other.sales...}

}

9

isSame method implement

7/16/2014

public class Star {private String firstName;private String lastName;private String instrument;private int sales;...

// check whether this star is same another starpublic boolean isSame(Star other) {

return (this.firstName.equals(other.firstName)&& this.lastName.equals(other.lastName)&& this.instrument.equals(other.instrument) && this.sales == other.sales);

}

10

isSame method test

7/16/2014

import junit.framework.TestCase;

public class StarTest extends TestCase {...public void testIsSame() {

assertTrue(new Star("Abba", "John", "vocals", 12200).isSame(new Star("Abba", "John", "vocals", 12200)));

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

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

Star aStar2 = new Star("Debie", "Gission", "organ", 15000);Star aStar3 = new Star("Debie", "Gission", "organ", 15000);assertFalse(aStar1.isSame(aStar2));assertTrue(aStar2.isSame(aStar3));

}} 11

isBiggerSales method template

7/16/2014

public class Star {private String firstName;private String lastName;private String instrument;private int sales;...// check whhether this star' sales is greater than // another star' salespublic boolean isBiggerSales(Star other) {

...this.firstName...this.lastName...

...this.instrument...this.sales...

...this.isSame(...)...

...other.firstName...other.lastName...

...other.instrument...other.sales...

...other.isSame(...)...}

}

12

isBiggerSales method implement

7/16/2014

public class Star {private String firstName;private String lastName;private String instrument;private int sales;...

// check whether this star is same another starboolean isBiggerSales(Star other) {

return (this.sales > other.sales);}

13

isBiggerSales method test

7/16/2014

import junit.framework.TestCase;

public class StarTest extends TestCase {...

public void testIsBiggerSales () {

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

assertTrue(new Star("Elton", "John", "guitar", 20000)

.isBiggerSales(aStar1));

assertFalse(aStar1.isBiggerSales(

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

}}

14

incrementSales method template

7/16/2014

public class Star {private String firstName;private String lastName;private String instrument;private int sales;...

// Adds 20.000 to the star's sales??? incrementSales() {

...this.firstName...

...this.lastName...

...this.instrument...

...this.sales...

...this.isSame(...)...

...this.isBiggerSales(...)...}

}

15

incrementSales method implement

• 2 implements– Immutable– Mutable

7/16/2014 16

incrementSales immutable

• creates a new star with a different sales.

7/16/2014

public class Star {private String firstName;private String lastName;private String instrument;private int sales;...

public boolean issame(Star other) { ... }public boolean isBiggerSales(Star other) { ... }

public Star incrementSales() {return new Star(this.firstName, this.lasttName,

this.instrument, this.sales + 20000);}

}

Immutable

17

Test incrementSales immutable method

7/16/2014

import junit.framework.*;public class StarTest extends TestCase {...public void testIncrementSales(){

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

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

.isSame(new Star("Elton", "John", "guitar", 40000)));

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

.isSame(new Star("Debie", "Gission", "organ", 35000)));}

}

18

mutableIncrementSales method

• Change sales of this object

7/16/2014

public class Star {private String firstName;private String lastName;private String instrument;private int sales;...public boolean issame(Star other) { ... }public boolean isBiggerSales(Star other) { ... }

// check whether this star is same another starpublic void mutableIncrementSales() {

this.sales = this.sales + 20000}

Mutable

19

Test mutableIncrementSales

7/16/2014

import junit.framework.*;public class TestStar extends TestCase {

...public void testMutableIncrementSales (){

Star aStar1 = new Star("Elton", "John", "guitar", 20000);Star aStar2 = new Star("Debie", "Gission", "organ", 15000);aStar1.mutableIncrementSales();assertEquals(40000, aStar1.getSales());aStar2. mutableIncrementSales();assertEquals(35000, aStar2.getSales());

}}

20

Discuss more: getSales method

• Q: Do we use “selector” this.sales outside Star class• A: No• Solution: getSales method

7/16/2014

public class Star {private String firstName;private String lastName;private String instrument;private int sales;...

public int getSales() {

return this.sales;

}

}

21

Class diagram

7/16/2014

Star- String firstName- String lastName- String instrument- int sales

+ Star incrementSales()+ void muatbleIncrementSales()+ boolean isSame(Star other)+ boolean isBiggerSales(Star orther)+ int getSales()

22

Exercise 2.1

• An old-style movie theater has a simple profit method. Each customer pays for ticket, for example $5. Every performance costs the theater some money, for example $20 and plus service charge per attendee, for example $.50.

• Develop the totalProfit method. It consumes the number of attendees (of a show) and produces how much income the attendees profit

• Example:– totalProfit(40) return $160

7/16/2014

Solution

23

Exercise 2.2

• A rocket is represent by model and manufacturer. Develop the height method, 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 v = g * t in t time units and a height of 1/2 * v * t where v is the speed at t.

7/16/2014

Solution

24

Exercise 2.3

• Design the following methods for this class: 1. isPortrait, which determines whether the image’s height is

larger than its width;2. size, which computes how many pixels the image contains;3. isLarger, which determines whether one image contains more

pixels than some other image; and4. same, which determines whether this image is the same as a

given one.

7/16/2014

• Take a look at this following class:// represent information about an imagepublic class Image {

private int width; // in pixelsprivate int height; // in pixelsprivate String source; // file nameprivate String quality; // informal

}

25

Conditional Computations

• . . . Develop a method that computes the yearly interest for certificates of deposit (CD) for banks. The interest rate for a CD depends on the amount of deposited money. Currently, the bank pays 2% for amounts up to $5,000, 2.25% for amounts between $5,000 and $10,000, and 2.5% for everything beyond that. . . .

7/16/2014 26

Define Class

public class CD {private String owner;private int amount; // cents

public CD(String owner, int amount) {this.owner = owner;this.amount = amount;

}}

7/16/2014 27

Example

• Translating the intervals from the problem analysis into tests yields three “interior” examples:– new CD("Kathy", 250000).interest() expect 5000.0– new CD("Matthew", 510000).interest() expect 11475.0– new CD("Shriram", 1100000).interest() expect 27500.0

7/16/2014 28

Conditional computation

• To express this kind of conditional computation, Java provides the so-called IF-STATEMENT, which can distinguish two possibilities:

if (condition) {statement1

}else {

statement2

}

if (condition) {statement1

}

7/16/2014 29

interest method template

7/16/2014

// compute the interest rate for this account public double interest() {

if (0 <= this.amount && this.amount < 500000) {...this.owner...this.amount...

}else {

if (500000 <= this.amount && this.amount < 1000000) {...this.owner...this.amount...

}else {

...this.owner...this.amount... }

}}

30

interest() method implement

7/16/2014

// compute the interest rate for this accountpublic double interest() {

if (0 <= this.amount && this.amount < 500000) {return 0.02 ∗ this.amount;

}else {

if (500000 <= this.amount && this.amount < 1000000) {return 0.0225 ∗ this.amount;

}else {

return 0.025 ∗ this.amount; }

}}

31

interest() different implement

7/16/2014

// compute the interest rate for this accountpublic double interest() {

if (this.amount < 0) return 0;

if (this.amount < 500000) return 0.02 ∗ this.amount;

if (this.amount < 1000000)return 0.0225 ∗ this.amount;

return 0.025 ∗ this.amount; }

32

Exercise 2.4

Modify the Coffee class so that cost takes into account bulk discounts:

. . . Develop a program that computes the cost of selling bulkcoffee at a specialty coffee seller from a receipt that includes the kind of coffee, the unit price, and the total amount (weight) sold. If the sale is for less than 5,000 pounds, there is no discount. For sales of 5,000 pounds to 20,000 pounds, the seller grants a discount of 10%. For sales of 20,000 pounds or more, the discount is 25%. . . .

7/16/2014 33

Exercise 2.4• Take a look at this following class:

7/16/2014

// represent information about an imagepublic class Image {

private int width; // in pixelsprivate int height; // in pixelsprivate String source;public Image(int width, int height, String source) {

this.width = width;this.height = height;this.source = source;

}}

34

Design the method sizeString produces one of three strings, depending on the number of pixels in the image (the area of the image):1. "small" for images with 10,000 pixels or fewer;2. "medium" for images with between 10,001 and 1,000,000 pixels;3. "large" for images that are even larger than that.

Exercise 2.5

Design the class JetFuel, whose purpose it is to represent the sale of some quantity of jet fuel.

Each instance contains the quantity sold (in integer gallons), the quality level (a string), and the current base price of jet fuel (in integer cents per gallon). The class should come with two methods:

– totalCost, which computes the cost of the sale, – discountPrice, which computes the discounted price. The

buyer gets a 10% discount if the sale is for more than 100,000 gallons

7/16/2014 35

7/16/2014

Relax…

& Do Exercise

36

Student example

• Information about a student includes id, first name, last name and his head teacher.

• Develop check method, is supposed to return the last name of the student if the teacher's name is equal to aTeacher and “ none” otherwise.

• Transfer student for another head teacher.

7/16/2014 37

Class diagram

7/16/2014

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

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

Property or field

Method

Data type

Class

38

Define Class and Constructor

7/16/2014

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

this.id = id;this.firstName = firstName;this.lastName = lastName;this.teacher = teacher;

}}

39

Test Student Constructor

7/16/2014

import junit.framework.*;

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

new Student("st1", "Find", "Matthew", "Fritz");Student aStudent1 =

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

new Student("st3", "Woops", "Helen", "Flatt");}

}

40

check method template

7/16/2014

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) {this.id = id;this.firstName = firstName;this.lastName = lastName;this.teacher = teacher;

}//

public String check(String thatTeacher) {

...this.id...

...this.firstName...

...this.lastName...

...this.teacher...}

}

41

check method body

7/16/2014

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) {this.id = id;this.firstName = firstName;this.lastName = lastName;this.teacher = teacher;

}

public String check(String thatTeacher) {if (this.teacher.equals(thatTeacher))

return this.lastName;return "none";

}}

42

Test check

7/16/2014

import junit.framework.*;

public class StudentTest extends TestCase {...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"));

}}

43

Class diagram

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

+ String check(String thatTeacher)+ ??? transfer(???)

7/16/2014 44

transfer method template

7/16/2014

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

this.id = id;

this.firstName = firstName;

this.lastName = lastName;

this.teacher = teacher;}

public ??? transfer(???) {...this.id......this.firstName......this.lastName......this.teacher...

}} 45

transfer method body

7/16/2014

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

46

Test transfer method

7/16/2014

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", "Fillip","Lee")));

assertTrue(aStudent2.tranfer("Flister").equals(new Student("st3", "Woops", "Helen","Flister")));

}}

47

Discuss more: equals method• Q: Why we do not use JUnit built-in assertEquals method?• Our equals method:

7/16/2014 48

public class Student {private String id;private String firstName;private String lastName;private String teacher;...public boolean equals(Object obj) {

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

else {Student that = ((Student) obj);return this.id.equals(that.id)

&& this.firstName.equals(that.firstName)&& this.lastName.equals(that.lastName)&& this.teacher.equals(that.teacher);

}}

}

mutableTransfer method body

7/16/2014

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) {this.id = id;this.firstName = firstName;this.lastName = lastName;this.teacher = teacher;

}

public void mutableTransfer(String thatTeacher){this.teacher = thatTeacher;

}}

mutable

49

Discuss more: getTeacher method

Q: Do we use “selector” this.teacher outside Student classA: NoSolution : getTeacher method

7/16/2014

public class Student {private String id;private String firstName;private String lastName;private String teacher;...

public String getTeacher(){return this.teacher;

}}

50

Test mutableTransfer method

7/16/2014

import junit.framework.*;

public class TestStudent extends TestCase {...public void testMutableTransfer() {

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

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

aStudent1.mutableTransfer("Lee");assertEquals("Lee", aStudent1.getTeacher());

aStudent2.mutableTransfer("Flister"); assertEquals("Flister", aStudent2.getTeacher());

}}

51

Class diagram

7/16/2014

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

Method

Data type

Class

52

Exercise 2.6

• Develop whatKind method. The method consumes the coefficients a, b, and c of a quadratic equation. It then determines whether the equation is degenerate and, if not, how many solutions the equation has. The method produces one of four symbols: "degenerate", "two", "one", or "none".

7/16/2014

Solution

53

Exercise 2.7

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

• Develop the method 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% per year for deposits of up to $1,000, a flat 4.5% for deposits of up to $5,000, and a flat 5% for deposits of more than $5,000

7/16/2014

Solution

54

Exercise 2.8

• 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 payback method, which consumes a charge amount and computes the corresponding pay-back amount.

7/16/2014

Solution

55

Relax…

& Do Exercise

7/16/2014 56

Solution 2.1public 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;

}private double cost(int numAttendee) {

return this.costForPerformance + this.costPerAttendee * numAttendee;

}private double revenue(int numAttendee) {

return this.ticketPrice * numAttendee;} public double totalProfit(int numAttendee) {

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

}

7/16/2014 57

Solution 2.1 (cont): Using test

7/16/2014Back

public void testTotalProfit() {MovieTheatre aMovie1 = new MovieTheatre(5.0, 20.0, 0.15);MovieTheatre aMovie2 = new MovieTheatre(6.0, 40.0, 0.1);MovieTheatre aMovie3 = new MovieTheatre(7.0, 50.0, 0.2);assertEquals(465.0, aMovie1.totalProfit(100), 0.001);assertEquals(550.0, aMovie2.totalProfit(100), 0.001);assertEquals(630.0, aMovie3.totalProfit(100), 0.001);

}

58

Solution 2.2

7/16/2014

public class Rocket {private String model;private String manufacturer;public Rocket(String model, String manufacturer) {

this.model = model;this.manufacturer = manufacturer;

}

public double speed(double time) {return 10 * time;

}

public double height(double time) {return 0.5 * this.speed(time) * time;

}}

59

Solution 2.2: Using test

7/16/2014Back

public void testHeight() {Rocket aRocket1 = new Rocket("Columbia", "America");Rocket aRocket2 = new Rocket("Victory", "England");Rocket aRocket3 = new Rocket("Win", "Vietnam");assertEquals(500.0 , aRocket1.height(10), 0.001);assertEquals(2000.0, aRocket2.height(20), 0.001);assertEquals(4500.0, aRocket3.height(30), 0.001);

}

60

Solution 2.6: Class definition

7/16/2014

public class Quadratic {

private double a;

private double b;

private double c;

public Quadratic(double a, double b, double c) {

this.a = a;

this.b = b;

this.c =c;}

public double computeDelta() {

return this.b * this.b - 4 * this.a * this.c;}

public String whatKind() {

double delta = this.computeDelta();

if (this.a == 0) return "degenerate";

if (delta < 0) return "none";

if (delta == 0) return "one solution";

return "two solution"; }

}61

Solution 2.6 (cont): Using test

7/16/2014Back

public void testWhatKind() {Quadratic q1= new Quadratic(0.0, 1.0, 2.0);Quadratic q2= new Quadratic(2.0, 1.0, 2.0);Quadratic q3= new Quadratic(1.0, 2.0, 1.0);Quadratic q4= new Quadratic(2.0, 3.0, 1.0);assertEquals("degenerate", q1.whatKind());assertEquals("none", q2.whatKind());assertEquals("one solution", q3.whatKind());assertEquals("two solution", q4.whatKind());

}

62

Solution 2.7: Class definition

7/16/2014

public class Transaction {private String customerName;private double depositeAmount;private int maturity;public Transaction(String customerName,

double depositeAmount, int maturity) {this.customerName = customerName;this.depositeAmount = depositeAmount;this. maturity = maturity;

}public double interest() {

if (this.depositeAmount <= 1000)return this.depositeAmount * 0.04;

if (this.depositeAmount <= 5000)return this.depositeAmount * 0.045 ;

return this.depositeAmount * 0.05 ;}

}

63

Solution 2.7 (cont): Using test

7/16/2014Back

public void testInterest(){Transaction t1 = new Transaction("Thuy", 6000, 2);Transaction t2 = new Transaction("Mai", 2500, 1);Transaction t3 = new Transaction("Nam", 1500, 2);Transaction t4 = new Transaction("Tien", 500, 2);assertEquals(300.0, t1.interest(), 0.001);assertEquals(112.5, t2.interest(), 0.001);assertEquals(67.5, t3.interest(), 0.001);assertEquals(20.0, t4.interest(), 0.001);

}

64

Solution 2.8: Method implementation

7/16/2014

public double payback() {if (this.depositeAmount <= 500)

return this.depositeAmount * 0.0025;if (this.depositeAmount <= 1500)

return 500 * 0.0025 + (this.depositeAmount - 500)* 0.005 ;if (this.depositeAmount <= 2500 )

return 500 * 0.0025 + 1000 * 0.005 + (this.depositeAmount -1500)* 0.0075;

return 500 * 0.0025 + 1000 * 0.005 + 1000 * 0.0075 + (this.depositeAmount - 2500)* 0.01;

}

65

Solution 2.8 (cont) Using test

7/16/2014Back

public void testPayback() {Transaction t1 = new Transaction("Thuy", 6000, 2);Transaction t2 = new Transaction("Mai", 2500, 1);Transaction t3 = new Transaction("Nam", 1500, 2);Transaction t4 = new Transaction("Tien", 500, 2);assertEquals(48.75, t1.payback(), 0.001);assertEquals(13.75, t2.payback(), 0.001);assertEquals(6.25, t3.payback(), 0.001);assertEquals(1.25, t4.payback(), 0.001);

}

66