2. The public or private modifiers
for 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
3. 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
4. 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
5. 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
6. 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
7. Define Class and Constructor
7/16/2014
public class Star {
private String firstName;
private String lastName;
private String instrument;
private int sales;
// contructor
public Star(String firstName, String lastName,
String instrument, int sales) {
this.firstName = firstName;
this.lastName = lastName;
this.instrument = instrument;
this.sales = sales;
}
}
7
8. 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
9. Compare equals of 2 objects
Check 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 star
public boolean isSame(Star other) {
...this.firstName...this.lastName...
...this.instrument...this.sales...
...other.firstName...other.lastName...
...other.instrument...other.sales...
}
}
9
10. 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 star
public 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
11. 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
12. 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' sales
public 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
13. 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 star
boolean isBiggerSales(Star other) {
return (this.sales > other.sales);
}
13
14. 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
15. 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
17. 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
18. 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
19. 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 star
public void mutableIncrementSales() {
this.sales = this.sales + 20000
}
Mutable
19
20. 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
21. 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
22. 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
23. 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
24. 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
25. 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; and
4. 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 image
public class Image {
private int width; // in pixels
private int height; // in pixels
private String source; // file name
private String quality; // informal
}
25
26. 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
27. 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
28. 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
29. 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
30. 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
31. interest() method implement
7/16/2014
// compute the interest rate for this account
public 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
32. interest() different implement
7/16/2014
// compute the interest rate for this account
public 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
33. 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
34. Exercise 2.4
• Take a look at this following class:
7/16/2014
// represent information about an image
public class Image {
private int width; // in pixels
private int height; // in pixels
private 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.
35. 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
37. 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
38. Class diagram
7/16/2014
Student
+ String id
+ String firstName
+ String lastName
+ String teacher
+ ??? check(???)
+ ??? transfer(???)
Property or field
Method
Data type
Class
38
39. 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
40. 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
50. Discuss more: getTeacher method
Q: Do we use “selector” this.teacher outside Student class
A: No
Solution: 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
51. 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
52. 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
53. 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
54. 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
55. 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