2-Methods For Classes
2-Methods For Classes
1
Expressions
Computing with Primitive Types
• For the primitive types int, double, and boolean,
Java supports a notation for expressions that
appeals to the one that we use in arithmetic and
algebra courses.
• For example, we can write
– 10 ∗ 12.50
– width + height
– Math.PI ∗ radius
2
Arthimetic and Relation Operators
Symbol Parameter types Result Example
+ numeric, numeric numeric x+2 addition
- numeric, numeric numeric x–2 subtraction
* numeric, numeric numeric x*2 multiplication
/ numeric, numeric numeric x/2 division
% integer, integer integer x%y modulo
• Example
(x != 0) && (x < 10) . . . determines whether a is not
equal to x (int or double) and x is less than 10
4
Expressions - Method Calls
• A method is roughly like a function. Like a function, a
method consumes data and produces data.
• However, a METHOD is associated with a class.
• Example:
– To compute the length of the string in Java,
we use the length method from the String class like this:
"hello world".length()
– To concatenate "world" to the end of the argument "hello"
String str = "hello";
str.concat("world")
– Math.sqrt(10) is square of 10
5
Method Calls
• When the method is called, it always receives at
least one argument: an instance of the class with
which the method is associated;
• Speaks of INVOKING a method on an instance or
object
6
Design Class Method Steps
The design of methods follows the same design
recipes
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
Design Class Method Steps
3. Examples
– the creation of examples that illustrate the purpose
statement in a concrete manner
4. Method 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
8
Coffee Seller Example
Take a look at this revised version of our first problem
. . . Design a method that computes the cost of selling
bulk coffee at a specialty coffee seller from a receipt
that includes the kind of coffee, the unit price, and the
total amount (weight) sold. . .
• Examples
1) 100 pounds of Hawaiian Kona at $15.95/pound
® $1,595.00
2) 1,000 pounds of Ethiopian coffee at $8.00/pound
® $8,000.00
3) 1,700 pounds of Colombian Supreme at $9.50/pound
® 16,150.00
9
1. Problem analysis and data definitions
class Coffee { Coffee
String kind;
double price; - String kind
double weight; - double price
Coffee(String kind, double price,
- double weight
double weight) {
this.kind = kind;
this.price = price;
this.weight = weight;
}
} import junit.framework.*;
public class CoffeeTest extends TestCase {
public void testConstructor() {
new Coffee("Hawaiian Kona", 15.95, 100);
new Coffee("Ethiopian", 8.0, 1000);
new Coffee("Colombian Supreme ", 9.5, 1700);
}
} 10
1. Problem analysis and data definitions
• Methods are a part of a class. Coffee
- String kind
• Thus, if the Coffee class already - double price
had a cost method, we could write: - double weight
new Coffee("Kona", 15.95, 100).cost()
??? cost(???)
and expect this method call
to produce 1595.0.
• The only piece of information the method needs is
the instance of the class Coffee for which we are
computing the selling cost.
• It will produce a double value that represents the
selling cost.
11
2. Purpose and contract
• First we add a contract, a purpose statement,
and a header for cost to the Coffee class
// the bill for a Coffee sale
class Coffee {
String kind;
double price; // in dollars per pound
double weight; // in pounds
Coffee(String kind, double price, double weight) {
...
}
13
3. Examples
• new Coffee("Hawainian Kona", 15.95,
100).cost()
// should produce 1595.0
• new Coffee("Ethiopian", 8.0, 1000).cost()
// should produce 8000.0
• new Coffee("Colombian", 9.5, 1700).cost()
// should produce 16150.0
14
4. cost method template and result
// to compute the total cost of this coffee purchase
// [in cents]
double cost() {
...this.kind...
...this.price...
...this.weight...
}
15
5. Coffee class and method
class Coffee {
String kind;
double price;
double weight;
16
6. Test cost method
import junit.framework.TestCase;
public class CoffeeTest extends TestCase {
public void testContructor() {
...
}
17
Methods consume more data
Design method to such problems:
… The coffee shop owner may wish to find out
whether a coffee sale involved a price over a certain
amount …
Coffee
- String kind
- double price
- double weight
double cost()
??? priceOver(???)
18
Purpose statement and signature
• This method must consume two arguments:
– given instance of coffee: this
– a second argument, the number of dollars with
which it is to compare the price of the sale’s record.
inside of Coffee
// to determine whether this coffee’s price is more
// than amount
boolean priceOver(double amount) { ... }
19
Examples
• new Coffee("Hawaiian Kona", 15.95,
100).priceOver(12)
expected true
21
Test priceOver method
import junit.framework.TestCase;
public class CoffeeTest extends TestCase {
...
22
Catesian Point example
• Suppose we wish to represent the pixels
(colored dots) on our computer monitors.
– A pixel is very much like a Cartesian point. It has an x
coordinate, which tells us where the pixel is in the
horizontal direction, and it has a y coordinate, which
tells us where the pixel is located in the downwards
vertical direction.
– Given the two numbers, we can locate a pixel on the
monitor
• Computes how far some pixel is from the origin
• Computes the distance between 2 pixels
23
Class diagram, Define Class and Test
class CartPt {
CartPt int x;
int x int y;
int y CartPt(int x, int y) {
this.x = x;
this.y = y;
}
}
import junit.framework.*;
public class CartPtTest extends TestCase {
public void testConstrutor() {
new CartPt(5, 12);
CartPt aCartPt1 = new CartPt(0, 3);
CartPt aCartPt2 = new CartPt(3, 4);
}
}
24
Computes
How far some pixel is from the origin
CartPt
int x
int y
??? distanceToO(???)
??? distanceTo(???)
25
distanceToO method signature
inside of CartPt
// Computes how far this pixel is from the origin
double distanceToO() { ... }
• Examples
– new CartPt(5, 12).distanceToO() should be
13.0
– new CartPt(0, 3).distanceToO() should be 3.0
– new CartPt(4, 7).distanceToO() should be
8.062
26
distanceToO method template
class CartPt {
int x;
int y;
CartPt(int x, int y) {
this.x = x;
this.y = y;
}
27
distanceToO method implementation
class CartPt {
int x;
int y;
CartPt(int x, int y) {
this.x = x;
this.y = y;
}
28
Test distanceToO method
import junit.framework.*;
public class CartPtTest extends TestCase {
...
29
Computes the distance
between 2 pixels
CartPt
int x
int y
double distanceToO()
??? distanceTo(???)
30
distanceTo Method Signature
inside of CartPt
// Computes distance from this CartPt to another
CartPt
double distanceTo(CartPt that) { ... }
• Examples
– new CartPt(6, 8).distanceTo(new CartPt(3,
4))
should be 5.0
– new CartPt(0, 3).distanceToO(new CartPt(4,
0)) should be 5.0
– new CartPt(1, 2).distanceToO(new CartPt(5,
3))
should be 4.123 31
distanceTo method template
class CartPt {
int x;
int y;
...
// Computes how far this pixel is from the origin
double distanceToO() {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
32
distanceTo method implement
class CartPt {
int x;
int y;
...
// Computes how far this pixel is from the origin
double distanceToO() {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
33
Test distanceTo method
import junit.framework.*;
public class CartPtTest extends TestCase {
...
}
}
34
Class diagram - Final
CartPt
int x
int y
double distanceToO()
double distanceTo(CartPt that)
35
Object Compare
36
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's sales is greater than
another star's sales.
– Check whether one star is same another star.
37
Class Diagram
Class
Star
String firstName
String lastName
Property or field
Data type String instrument
int sales
Method
38
Define Class and Constructor
class Star {
String firstName;
String lastName;
String instrument;
int sales;
// contructor
Star(String firstName, String lastName,
String instrument, int sales) {
this.firstName = firstName;
this.lastName = lastName;
this.instrument = instrument;
this.sales = sales;
}
}
39
Test Star Constructor
import junit.framework.*;
40
Check whether one star's sales is
greater than another star's sales.
Star
String firstName
String lastName
String instrument
int sales
??? biggerSales(???)
• Examples
new Star("Elton", "John", "guitar", 20000)
.biggerSales(new Star("Abba", "John", "vocals", 12200))
expected true
41
biggerSales method template
class Star {
String firstName;
String lastName;
String instrument;
int sales;
...
42
biggerSales method implement
class Star {
String firstName;
String lastName;
String instrument;
int sales;
...
43
biggerSales method test
import junit.framework.TestCase;
44
Compare equals of 2 objects
• Check whether one star is same another star.
Star
String firstName
String lastName
String instrument
int sales
boolean biggerSales(Star other)
??? same(???)
45
same() method template
class Star {
String firstName;
String lastName;
String instrument;
int sales;
...
47
same method test
import junit.framework.TestCase;
public class StarTest extends TestCase {
...
public void testSame() {
assertTrue(new Star("Abba", "John", "vocals", 12200)
.same(new Star("Abba", "John", "vocals", 12200)));
50
Conditional Computations
51
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. . . .
52
Define Class
class CD {
String owner;
int amount; // cents
53
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
54
Conditional computation
• To express this kind of conditional computation,
Java provides the so-called IF-STATEMENT, which
can distinguish two possibilities:
if (condition) { if (condition) {
statement1 statement1
} }
else {
statement2
}
55
interest method template
// compute the interest rate for this account
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...
}
}
}
56
interest() method implement
// compute the interest rate for this account
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;
}
}
}
57
interest() full implement
// compute the interest rate for this account
double interest() {
if (this.amount < 0) {
return 0;
}
else {
if (this.amount < 500000) {
return 0.02 ∗ this.amount;
}
else {
if (this.amount < 1000000) {
return 0.0225 ∗ this.amount;
}
else {
return 0.025 ∗ this.amount;
}
}
}
} 58
interest() different implement
// compute the interest rate for this account
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;
}
59
Mutable and Inmutable methods
60
Star example
• Suppose we wish to represent a star information
which has first name, last name, instrument he uses
and his sales.
• Design methods:
– Adds 20.000 to the star's sales.
61
Adds 20.000 to the star's sales.
Star
String firstName
String lastName
String instrument
int sales
??? biggerSales(???)
??? same(???)
??? incrementSales(???)
66
Test mutableIncrementSales
import junit.framework.*;
aStar1.mutableIncrementSales();
assertEquals(40000, aStar1.getSales());
aStar2.mutableIncrementSales();
assertEquals(35000, aStar2.getSales());
}
}
67
Discuss more: getSales method
• Q: Do we use “selector” this.sales outside Star class
• A: No
• Solution: getSales method
class Star {
String firstName;
String lastName;
String instrument;
int sales;
...
int getSales() {
return this.sales;
}
}
68
Class diagram
Star
String firstName
String lastName
String instrument
int sales
Star incrementSales()
void muatbleIncrementSales()
boolean same(Star other)
boolean biggerSales(Star orther)
int getSales()
69