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 "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 (object) 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
Primary argument: this
• cost method is always invoked on some specific
instance of Coffee.
– The instance is the primary argument to the
method, and it has a standard name, this
• We can thus use this to refer to the instance of
Coffee and access to three pieces of data:
the kind, the price, and the weight in method
body
– Access field with: object.field
– E.g: this.kind, this.price, this.weight
14
4. cost method template
// to compute the total cost of this coffee purchase
// [in cents]
double cost() {
...this.kind...
...this.price...
...this.weight...
}
15
5. cost method result
• The two relevant pieces are this.price and
this.weight. If we multiply them, we get the
result that we want:
16
5. Coffee class and method
class Coffee {
String kind;
double price;
double weight;
17
6. Test cost method
import junit.framework.TestCase;
public class CoffeeTest extends TestCase {
public void testContructor() {
...
}
18
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(???)
19
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.
20
Examples
• new Coffee("Hawaiian Kona", 15.95, 100)
.priceOver(12)
expected true
22
Test priceOver method
import junit.framework.TestCase;
public class CoffeeTest extends TestCase {
...
23
Cartesian 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
24
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);
}
}
25
Computes
How far some pixel is from the origin
CartPt
int x
int y
??? distanceToO(???)
26
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
27
distanceToO method template
class CartPt {
int x;
int y;
CartPt(int x, int y) {
this.x = x;
this.y = y;
}
28
distanceToO method implementation
class CartPt {
int x;
int y;
CartPt(int x, int y) {
this.x = x;
this.y = y;
}
29
Test distanceToO method
import junit.framework.*;
public class CartPtTest extends TestCase {
...
30
Computes the distance
between 2 pixels
CartPt
int x
int y
double distanceToO()
??? distanceTo(???)
31
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).distanceTo(new CartPt(4,
0)) should be 5.0
– new CartPt(1, 2).distanceTo(new CartPt(5,
3)) should be 4.123
32
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);
}
33
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);
}
34
Test distanceTo method
import junit.framework.*;
public class CartPtTest extends TestCase {
...
}
}
35
Class diagram - Final
CartPt
int x
int y
double distanceToO()
double distanceTo(CartPt that)
36
Object Compare
37
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.
38
Class Diagram
Class
Star
String firstName
String lastName
Property or field
Data type String instrument
int sales
Method
39
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;
}
}
40
Test Star Constructor
import junit.framework.*;
41
Check whether one star's sales is
greater than another star's sales.
Star
String firstName
String lastName
String instrument
int sales
??? biggerSales(???)
42
biggerSales() Method Signature
inside of Star class
// check whether this star’s sales is greater than
// another star’s sales
boolean biggerSales(Star other) { ... }
• Examples
new Star("Elton", "John", "guitar", 20000)
.biggerSales(new Star("Abba", "John",
"vocals", 12200)) expected true
new Star("Abba", "John", "vocals", 12200)
.biggerSales(new Star("Debie", "Gission",
"organ", 15000)) expected false
43
biggerSales() method template
class Star {
String firstName;
String lastName;
String instrument;
int sales;
...
44
biggerSales method implement
class Star {
String firstName;
String lastName;
String instrument;
int sales;
...
45
biggerSales() method test
import junit.framework.TestCase;
46
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(???)
47
same() Method Signature
inside of Star class
// check whether this star is same another star
boolean same(Star other) { ... }
• Examples
new Star("Elton", "John", "guitar", 20000)
.same(new Star("Elton", "John", "guitar",
20000)) expected true
new Star("Elton", "John", "guitar", 20000)
.same(new Star("Debie", "Gission", "organ",
15000)) expected false
48
same() method template
class Star {
String firstName;
String lastName;
String instrument;
int sales;
...
50
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)));
53
Conditional Computations
54
Conditional Computation Example
• . . . 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. . . .
55
Define Class
CD
String owner
int amount
class CD {
String owner;
int amount; // cents
56
interest method signature
CD
String owner
int amount
??? interest(???)
57
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
58
Conditional computation
• To express this kind of conditional computation,
Java provides the so-called IF-STATEMENT, which
can distinguish two possibilities:
if (condition) { if (condition1) {
statement1 statement1
} }
else {
if (condition2) {
if (condition) {
statement2
statement1
}
}
else {
else {
statement3
statement2
}
}
}
59
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...
}
}
}
60
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;
}
}
}
61
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;
}
}
}
} 62
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;
}
63
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;
}
64