You are on page 1of 93

Compound Data: Class

Compound Data - Class 1


Topic
• How to Design Program
– What is program and design program?
– Basic steps of a program design
• The Varieties of Data
• Compound Data: Class
• Design Class
• Design method

Compound Data - Class 2


How To Design program

Compound Data - Class 3


What is Program?
• A computer program is a set of ordered instructions
for a computer to perform a specific task or to exhibit
desired behaviors.
• Without programs, computers are useless.

• A software application or software program is the


most commonly found software on the computer.
– Microsoft Word is a word processor program that allows
users to create and write documents.

Compound Data - Class 4


What is Programming?
• Computer programming is the process of
designing, writing, testing, debugging, and
maintaining the source code of computer programs.
• Programming language:
– The source code of program is written as a series of
human understandable computer instructions in a that can
be read by a compiler, and translated into machine code
so that a computer can understand and run it.
– There are many programming languages such as C++,
C#, Java, Python, Smalltalk, etc.

Compound Data - Class 5


Design Program
• The process of programming often requires
expertise in many different subjects, including
knowledge of the application domain, specialized
algorithms and formal logic.
• Main goal of the design process is to lead from
problem statements to well-organized solutions
• Design guidelines are formulated as a number of
program design recipes.
– A design recipe guides a beginning programmer
through the entire problem-solving process

Compound Data - Class 6


How to Design Program
To design a program properly, a programmer must:
1. analyze a problem statement, typically stated as a
word problem;
2. express its essence, abstractly and with examples;
3. formulate statements and comments in a precise
language;
4. evaluate and revise these activities in light of
checks and tests; and
5. pay attention to details.

Compound Data - Class 7


Basic steps of a program design recipe
1. Problem Analysis & Data Definition
– the description of the class of problem data
2. Contract, Purpose & Effect Statements, Header
– the informal specification of a program's behavior
3. Examples
– the illustration of the behavior with examples
4. method Template
– the development of a program template or layout
5. method Definition
– the transformation of the template into a complete definition; and
6. Tests
– the discovery of errors through testing.

Compound Data - Class 8


Why Java?
• Object-oriented programming languages
• Open source
• A cross platform language
– Portability: "Write Once, Run Anywhere"
• Spread Rapidly through WWW and Internet

• JVM (Java Virtual Machine)


• JRE (Java Runtime Environment)
• JDK (Java Deverloper Kit)

Compound Data - Class 9


IDE
• IDE: Integrated Development Environment
– Netbean: supported by Sun
– Eclipse: open source, supported by IBM

Compound Data - Class 10


The Varieties of Data

Compound Data - Class 11


Primitive Forms of Data
• Java provides a number of built-in atomic forms of
data with which we represent primitive forms of
information.

Compound Data - Class 12


12
Integer type
Default
Name Size Range
value
byte 1 byte -128…127 0
short 2 bytes -32,768…32,767 0
int 4 bytes -2,147,483,648 to 0
2,147,483,648
long 8 bytes -9,223,372,036,854,775,808 to 0L
9,223,372,036,854,775,808

Compound Data - Class 13


Decimal type
Name Size Range Default
value
float 4 bytes ±1.4 x 10-45 ±3.4 x 1038 0.0f

double 8 bytes ±4.9 x 10-324 ±1.8 x 10308 0.0d

Compound Data - Class 14


14
Character type
Java represent a Unicode character (2 bytes)

Name Size Range Default value


char 2 bytes \u0000 … \uFFFF \u0000

• Q: Distinguish char type and String type ?


• A:
– char c = 't';
– String s = "tin hoc";

Compound Data - Class 15


15
Boolean type

Name Size Range Default value


boolean 1 byte false, true false

Compound Data - Class 16


16
String
• Strings to represent symbolic.
Symbolic information means the names of people,
street addresses, pieces of conversations, …
• a String is a sequence of keyboard characters
enclosed in quotation marks
– "bob"
– "#$%ˆ&"
– "Hello World"
– "How are U?"
– "It is 2 good to B true."

Compound Data - Class 17


Compound Data: Classes
• For many programming problems, we need more
than atomic forms of data to represent the relevant
information.

• Consider the following problem:

Compound Data - Class 18


Coffee example
• Develop a program 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

Compound Data - Class 19


Class Diagram: abstractly express

Class Name

CoffeeReceipt
- String kind
Property
Data type - double pricePerPound or field
- double weight
Method

Compound Data - Class 20


Define Java Class, Constructor
class definition

class CoffeeReceipt {
Field declarations. Each declaration
String kind; specifies the type of values that the field
double pricePerPound; name represents. Accordingly, kind
double weight; stands for a String and pricePerPound
and weight are doubles
CoffeeReceipt(String kind,
double pricePerPound, double weight) {
this.kind = kind;
this.pricePerPound = pricePerPound;
this.weight = weight;
}
} CONSTRUCTOR
of the class

Compound Data - Class 21


About Constructor
• Constructor name is same class name.
• The parameters of a constructor enclose in ()
quotes, separated by commas (,).
• Its body is a semicolon-separated (;) series of
statement this.fieldname = parametername;
CoffeeReceipt(String kind, double pricePerPound,
double weight) {
this.kind = kind;
this.price = price;
this.weight = weight;
}

Compound Data - Class 22


Translate sample
• It is best to translate some sample pieces of
information into the chosen representation.
• This tests whether the defined class is adequate for
representing some typical problem information.
• Apply the constructor to create an object (instance)
of the CoffeeReceipt class:
– new CoffeeReceipt("Hawaiian Kona", 15.95, 100)
– new CoffeeReceipt("Ethiopian", 8.00, 1000)
– new CoffeeReceipt("Colombia Supreme", 9.50, 1700)

Compound Data - Class 23


Test Class
Import test unit library
Define class CoffeeReceiptTest
import junit.framework.*; is test case.

public class CoffeeReceiptTest extends TestCase {


Test method that name is testXXX
public void testConstructor() {
new CoffeeReceipt("Hawaiian Kona", 15.95, 100);
new CoffeeReceipt("Ethiopian", 8.0, 1000);
new CoffeeReceipt("Colombian Supreme ", 9.5, 1700);
}
}

This tests contain statement to create an object of the CoffeeReceipt class, you
apply the constructor to as many values as there are parameters:
new CoffeeReceipt("Hawaiian Kona", 15.95, 100)
Compound Data - Class 24
Date example
• Develop a program that helps you keep track of
daily. One date is described with three pieces of
information: a day, a month, and a year

• Class diagram

Date
- int day
- int month
- int year

Compound Data - Class 25


Define Class, Constructor and Test
class Date {
int day;
int month;
int year;
Date(int day, int month, int year) {
this.day = day;
this.month = month;
this.year = year;
}
}

import junit.framework.*;
public class DateTest 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
}
}
Compound Data - Class 26
GPS Location example
• Develop a GPS navigation program for cars. The
physical GPS unit feeds the program with the
current location. Each such location consists of two
pieces of information: the latitude and the longitude.

• Class diagram
GPSLocation
- double latitude
- double longitude

Compound Data - Class 27


Define Class, Constructor and test
class GPSLocation {
double latitude /* degrees */;
double longitude /* degrees */;
GPSLocation(double latitude, double longitude) {
this.latitude = latitude;
this.longitude = longitude;
}
}

import junit.framework.*;
public class GPSLocationTest extends TestCase {
public void testConstrutor() {
new GPSLocation (33.5, 86.8);
new GPSLocation (40.2, 72.4);
new GPSLocation (49.0, 110.3);
}
}
Compound Data - Class 28
Three steps in designing Classes
1. Read the problem statement.
Look for statements that mention or list the
attributes of the objects in your problem space.
Write down your findings as a class diagram
because they provide a quick overview of classes.
2. Translate the class diagram into a class definition,
adding a purpose statement to each class.
3. Obtain examples of information and represent
them with instances of the class.
Conversely, make up instances of the class and
interpret them as information.
Compound Data - Class 29
Excercice 1.1
• Develop a program that assists bookstore
employees. For each book, the program should
track the book’s title, its price, its year of
publication, and the author’s name…
• Develop an appropriate class diagram (by hand) and
implement it with a class. Create instances of the
class to represent these three books:
1. Daniel Defoe, Robinson Crusoe, $15.50, 1719;
2. Joseph Conrad, Heart of Darkness, $12.80, 1902;
3. Pat Conroy, Beach Music, $9.50, 1996.

Compound Data - Class 30


Exercise 1.2
• Add a constructor to the following partial class definition
and draw the class diagram
// represent computer images
class Image {
int height; // pixels
int width; // pixels
String source; // file name
String quality; // informal
}
• Explain what the expressions mean in the problem
context and write test class:
new Image(5, 10, "small.gif", "low")
new Image(120, 200, "med.gif", "low")
new Image(1200, 1000, "large.gif", "high")

Compound Data - Class 31


Exercise 1.3
• Translate the class diagram in figure into a class
definition. Also create instances of the class

Automobile
- String model
- int price [in dollars]
- double mileage [in miles per gallon]
- boolean used

Compound Data - Class 32


Exercises 1.4
• Write Java class, constructor and test constructor for
representing points in time since midnight.
A point in time consists of three numbers: hours,
minutes, and seconds.

Compound Data - Class 33


Class Method

Compound Data - Class 34


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

Compound Data - Class 35


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

> numeric numeric x>2 greater than


>= numeric, numeric numeric x >= 2 greater or equal
< numeric, numeric numeric x<2 less than
<= numeric, numeric numeric x<2 less or equal
== numeric, numeric numeric x == 2 equal
!= numeric, numeric numeric x != 2 not equal
Compound Data - Class 36
Logic Operators
Symbol Parameter types Result Example

! boolean boolean !(x < 0) logical negation


&& boolean, boolean boolean a && b logical and
|| boolean, boolean boolean a || b logical or

• Example
(x != 0) && (x < 10) . . . determines whether a is not equal to
x (int or double) and x is less than 10

Compound Data - Class 37


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()
– String str = "hello";
str.concat("world")
concatenate "world" to the end of the argument "hello"
– Math.sqrt(10) is square of 10

Compound Data - Class 38


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;
– Because of that, a Java programmer does not speak of
calling functions for some arguments, but instead speaks
of INVOKING a method on an instance or object

• In general, a method call has this shape:


object.methodName(arg1, arg2, ...)

Compound Data - Class 39


Methods for Classes
• 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. . .

Compound Data - Class 40


Method example
• Methods are a part of a class.
• Thus, if the CoffeeReceipt class already had a
cost method, we could write:
new CoffeeReceipt("Kona", 15.95, 100).cost()
and expect this method call to produce 1595.0.
CoffeeReceipt
- String kind
- double pricePerPound
- double weight
??? cost(???)

Compound Data - Class 41


Designs through Templates
• First we add a contract, a purpose statement, and a
header for cost to the CoffeeReceipt class
// the bill for a CoffeeReceipt sale
class CoffeeReceipt {
String kind;
double pricePerPound; // in dollars per pound
double weight; // in pounds
CoffeeReceipt(String kind, double pricePerPound,
double weight) { ... }

// to compute the total cost of this coffee purchase


// [in dollars]
double cost() { ... }
a purpose statement
}
Contract is a METHOD SIGNATURE
Compound Data - Class 42
Primary argument: this
• cost method is always invoked on some specific
instance of CoffeeReceipt.
– 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
CoffeeReceipt and access to three pieces of data:
the kind, the pricePerPound, and the weight in
method body
– Access field with: object.field
– E.g: this.kind, this.pricePerPound, this.weight

Compound Data - Class 43


cost method template and result
// to compute the total cost of this coffee purchase
// [in cents]
double cost() {
...this.kind...
...this.pricePerPound...
...this.weight...
}

• the two relevant pieces are this.price and this.weight. If we


multiply them, we get the result that we want:
// to compute the total cost of this coffee purchase
// [in cents]
double cost() {
return this.pricePerPound * this.weight;
}
Compound Data - Class 44
CoffeeReceipt class and method
class CoffeeReceipt {
String kind;
double pricePerPound;
double weight;

CoffeeReceipt(String kind, double pricePerPound,


double weight) {
this.kind = kind;
this.pricePerPound = pricePerPound;
this.weight = weight;
}

// to compute the total cost of this coffee purchase


// [in dollars]
double cost() {
return this.pricePerPound * this.weight;
}
}
Compound Data - Class 45
Test cost method
import junit.framework.TestCase;
public class CoffeeReceiptTest extends TestCase {
public void testContructor() {
...
}

public void testCost() {


assertEquals(new CoffeeReceipt("Hawaiian Kona",
15.95, 100).cost(), 1595.0);
CoffeeReceipt c2 =
new CoffeeReceipt("Ethiopian", 8.0, 1000);
assertEquals(c2.cost(), 8000.0);
CoffeeReceipt c3 =
new CoffeeReceipt("Colombian Supreme ", 9.5, 1700);
assertEquals(c3.cost(), 16150.0);
}
}
Compound Data - Class 46
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 …

CoffeeReceipt
- String kind
- double pricePerPound
- double weight
double cost()
??? priceOver(???)

Compound Data - Class 47


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

Compound Data - Class 48


Examples
• new CoffeeReceipt("Hawaiian Kona", 15.95,
100).priceOver(12) expected true

• new CoffeeReceipt("Colombian Supreme", 9.50,


1700).priceOver(12) expected false

Compound Data - Class 49


priceOver method template and result
// to determine whether this coffee’s price
// is more than amount
boolean priceOver(int amount) {
... this.kind
... this.pricePerPound
... this.weight
... amount
}

The only relevant pieces of data in the template are amt and
this.price:
// to determine whether this coffee’s price
// is more than amount
boolean priceOver(int amount) {
return this.pricePerPound > amount;
}

Compound Data - Class 50


Test priceOver method
import junit.framework.TestCase;
public class CoffeeReceiptTest extends TestCase {
...

public void testPriceOver() {


CoffeeReceipt c1 =
new CoffeeReceipt("Hawaiian Kona", 15.95, 100);
CoffeeReceipt c2 =
new CoffeeReceipt("Ethiopian", 8.00, 1000);
CoffeeReceipt c3 =
new CoffeeReceipt("Colombian Supreme ", 9.50, 1700);
assertTrue(c1.priceOver(12));
assertFalse(c2.priceOver(12));
assertFalse(c3.priceOver(12));
}
}

Compound Data - Class 51


Posn 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

Compound Data - Class 52


Class diagram

Posn
- int x
- int y

+ ??? distanceTo0(???)
+ ??? distanceTo(???)

Compound Data - Class 53


Define Class, Constructor, and Test
class Posn {
int x;
int y;
Posn(int x, int y) {
this.x = x;
this.y = y;
}
}

import junit.framework.*;

public class PosnTest extends TestCase {


public void testConstrutor() {
new Posn(5, 12);
Posn aPosn1 = new Posn(6, 8);
Posn aPosn2 = new Posn(3, 4);
}
}
Compound Data - Class 54
Computes
How far some pixel is from the origin
Posn
- int x
- int y

+ ??? distanceToO(???)
+ ??? distanceTo(???)

• Examples
– Distance from A(5, 12) to O is 13
– Distance from B(6, 8) to O is 10
– Distance from A(3, 4) to O is 5

Compound Data - Class 55


distanceToO method template
class Posn {
int x;
int y;

Posn(int x, int y) {
this.x = x;
this.y = y;
}

// Computes how far this pixel is from the origin


double distanceToO() {
...this.x... Add a contract,
...this.y... a purpose statement
} METHOD SIGNATURE
}

Compound Data - Class 56


distanceToO method implementation
class Posn {
int x;
int y;

Posn(int x, int y) {
this.x = x;
this.y = y;
}

double distanceToO() {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
}

Compound Data - Class 57


Test distanceToO method
import junit.framework.*;
public class PosnTest extends TestCase {
public void testConstrutor(){
new Posn(5, 12);
Posn aPosn1= new Posn(6, 8);
Posn aPosn2 = new Posn(3, 4);
}

public void testDistanceToO(){


assertEquals(new Posn(5, 12).distanceToO(), 13.0, 0.001);
Posn aPosn1 = new Posn(6, 8);
assertEquals(aPosn1.distanceToO(), 10.0, 0.001);
Posn aPosn2 = new Posn(3, 4);
assertEquals(aPosn2.distanceToO(), 5.0, 0.001);
}
}

Compound Data - Class 58


Computes the distance between 2 pixels

Posn
- int x
- int y

+ double distanceToO()
+ ??? distanceTo(???)

• Example
– Distance from A(6, 8) to B(3, 4) is 5

Compound Data - Class 59


distanceTo method template
class Posn {
int x;
int y;
...
// Computes how far this pixel is from the origin
double distanceTo0(){
return Math.sqrt(this.x * this.x + this.y * this.y);
}

// Computes distance from this posn to another posn


double distanceTo(Posn that) {
...this.x...this.y...
...that.x...that.y... Add a contract,
...this.distantoO()...that.distanceToO()...
a purpose statement
}
METHOD SIGNATURE
}

Compound Data - Class 60


distanceTo method implement
class Posn {
int x;
int y;
...
// Computes how far this pixel is from the origin
double distanceTo0(){
return Math.sqrt(this.x * this.x + this.y * this.y);
}

// Computes distance from this posn to another posn


double distanceTo(Posn that) {
return Math.sqrt((that.x - this.x)*(that.x - this.x)
+ (that.y - this.y)*(that.y - this.y));
}
}

Compound Data - Class 61


Test distanceTo method
import junit.framework.*;
public class PosnTest extends TestCase {
...

public void testDistanceTo(){


assertEquals(new Posn(6, 8).distanceTo(
new Posn(3, 4)), 5.0, 0.001);

Posn aPosn1 = new Posn(6, 8);


Posn aPosn2 = new Posn(3, 4);
assertEquals(aPosn1.distanceTo(aPosn2), 5.0, 0.001);
}
}

Compound Data - Class 62


Class diagram - Final

Posn
- int x
- int y

+ double distanceToO()
+ double distanceTo(Posn that)

Compound Data - Class 63


Employee example
An employee has his name and the number of hours of work.
• Determines the wage of an employee from the number of
hours of work. Suppose 12 dollars per hour.
• Utopia's tax accountants always use programs that compute
income taxes even though the tax rate is a solid, never-
changing 15%. Determine the tax on the gross pay.
• Also determine netpay of an employee from the number of
hours worked base on gross pay and tax .
• Give everyone a raise to $14
• No employee could possibly work more than 100 hours per
week. To protect the company against fraud, the method
should check that the hours doesn’t exceed 100. If it does, the
method returns false. Otherwise, it returns true

Compound Data - Class 64


Class diagram

Employee
- String name
- int hours

+ ??? wage(???)
+ ??? tax(???)
+ ??? netpay(???)
+ ??? raisedWage(???)
+ ??? checkNotExceed100 (???)

Compound Data - Class 65


Define Class and Contructor and Test
public class Employee {
String name;
int hours;
Employee(String name, int hours) {
this.name = name;
this.hours = hours;
}
}

import junit.framework.*;
public class EmployeeTest extends TestCase {
public void testContructor() {
new Employee("Nam", 40);
Employee aEmployee1 = new Employee("Mai", 30);
Employee aEmployee2 = new Employee("Minh", 102);
}
}

Compound Data - Class 66


Compute wage
Employee
- String name
- int hours

+ ??? wage(???)
+ ??? tax(???)
+ ??? netpay(???)
+ ??? raisedWage(???)
+ ??? checkNotExceed100(???)

• Examples
– Employee Nam works 40 and earns 480 $
– Employee Mai works 30 and earns 360 $
– Employee Minh works 100 and earns 1200 $
Compound Data - Class 67
wage method template
public class Employee {
String name;
int hours;
Employee(String name, int hours) {
this.name = name;
this.hours = hours;
}

// Determines the wage of an employee


// from the number of hours of work
int wage() {
...this.name...
...this.hours...
}
}

Compound Data - Class 68


wage method body
class Employee {
String name;
int hours;
Employee(String name, int hours) {
this.name = name;
this.hours = hours;
}

// Determines the wage of an employee


// from the number of hours of work
int wage() {
return this.hours * 12;
}
}

Compound Data - Class 69


Test wage method
import junit.framework.*;
public class EmployeeTest extends TestCase {
...
public void testWage() {
assertEquals(new Employee("Nam", 40).wage(), 480);
Employee aEmployee1 = new Employee("Mai", 30);
Employee aEmployee2 = new Employee("Minh", 100);
assertEquals(aEmployee1.wage(), 360);
assertEquals(aEmployee2.wage(), 1200);
}
}

Compound Data - Class 70


Compute tax
Employee
- String name
- int hours

+ ??? wage(???)
+ ??? tax(???)
+ ??? netpay(???)
+ ??? raisedWage(???)
+ ??? checkNotExceed100(???)

• Examples
– Employee Nam gets 480 $ and has to pay 72 $ for tax
– Employee Mai gets 360 $ and has to pay 54 $ for tax
– Employee Minh gets 1200 $ and has to pay 180 $ for tax

Compound Data - Class 71


tax method template
class Employee {
String name;
int hours;
Employee(String name, int hours) {
this.name = name;
this.hours = hours;
}
int wage() {
return this.hours * 12;
}

// Determines the tax of an employee from the wage


double tax() {
...this.name...
...this.hours...
...this.wage()...
}
}
Compound Data - Class 72
tax method implement
class Employee {
String name;
int hours;
Employee(String name, int hours) {
this.name = name;
this.hours = hours;
}
int wage() {
return this.hours * 12;
}

// Determines the tax of an employee from the wage


double tax() {
// this.hours * 12 * 0.15;
return this.wage() * 0.15;
}
}
Compound Data - Class 73
Test tax method
import junit.framework.*;
public class EmployeeTest extends TestCase {
...
public void testTax() {
assertEquals(new Employee("Nam", 40).tax(), 72.0, 0.001);
Employee aEmployee1 = new Employee("Mai", 30);
Employee aEmployee2 = new Employee("Minh", 100);
Assert.assertEquals(aEmployee1.tax(), 54.0, 0.001);
Assert.assertEquals(aEmployee2.tax(), 180.0, 0.001);
}
}

Compound Data - Class 74


Class diagram
Employee
- String name
- int hours

+ ??? wage(???)
+ ??? tax(???)
+ ??? netpay(???)
+ ??? raisedWage(???)
+ ??? checkNotExceed100(???)

• Examples
– With salary 480 $, Nam just receives 408 $ of netpay
– With salary 360 $, Mai just receives 306 $ of netpay
– With salary 1200 $, Minh just receives 1020 $ of netpay

Compound Data - Class 75


netpay method template
public class Employee {
String name;
int hours;
Employee(String name, int hours) {
this.name = name;
this.hours = hours;
}

// Determines the netpay of an employee


double netpay() {
...this.name...
...this.hours...
...this.wage()...
...this.tax()...
}
}

Compound Data - Class 76


netpay method implement
class Employee {
String name;
int hours;
Employee(String name, int hours) {
this.name = name;
this.hours = hours;
}
int wage() {
return this.hours * 12;
}
double tax() {
return this.wage()) * 0.15;
}
// Determines the netpay of an employee
double netpay() {
return this.wage() - this.tax();
}
}
Compound Data - Class 77
Test netpay method
import junit.framework.*;
public class TestEmployee extends TestCase {
...
public void testNetpay() {
assertEquals(new Employee("Nam",40).netpay(),
408.0, 0.001);
Employee aEmployee1 = new Employee("Mai",30);
Employee aEmployee2 = new Employee("Minh",100);
Assert.assertEquals(aEmployee1.netpay(), 306.0, 0.01);
Assert.assertEquals(aEmployee2.netpay(), 1020.0, 0.01);
}
}

Compound Data - Class 78


Class diagram
Employee
- String name
- int hours

+ ??? wage(???)
+ ??? tax(???)
+ ??? netpay(???)
+ ??? raisedWage(???)
+ ??? checkNotExceed100(???)
• Examples
– With basic salary 480$, after getting bonus, total income of Nam
is 494
– With basic salary 360$, after getting bonus, total salary of Mai is
374
– With basic salary 1200$, after getting bonus, total salary of Minh
is 1214

Compound Data - Class 79


raisedWage method template
public class Employee {
String name;
int hours;
Employee(String name, int hours) {
this.name = name;
this.hours = hours;
}

// Raise the wage of employee with 14$


int raisedWage() {
...this.name...
...this.hours...
...this.wage()...
...this.tax()...
...this.netpay()...
}
}

Compound Data - Class 80


raisedWage method implement
class Employee {
String name;
int hours;
...
int wage() {
return this.hours * 12;
}
double tax() {
return this.wage() * 0.15;
}
double netpay() {
return this.wage() - this.tax();
}
// Raise the wage of employee with 14 $
int raisedWage() {
return this.wage() + 14;
}
}
Compound Data - Class 81
Test raisedWage method
import junit.framework.*;
public class TestEmployee extends TestCase {
...
public void testraisedWage(){
assertEquals(new Employee("Nam", 40).raisedWage(),
494, 0.001);
Employee aEmployee1 = new Employee("Mai", 30);
Employee aEmployee2 = new Employee("Minh", 100);
assertEquals(aEmployee1.raisedWage(), 374.0, 0.001);
assertEquals(aEmployee2.raisedWage(), 1214.0, 0.001);
}
}

Compound Data - Class 82


Class diagram
Employee
- String name
- int hours

+ ??? wage(???)
+ ??? tax(???)
+ ??? netpay(???)
+ ??? raisedWage(???)
+ ??? checkNotExceed100(???)

• Examples
– It is true that Nam and Mai work 40 and 30 hours per week
– It is impossible for Minh to work 100 hours per week

Compound Data - Class 83


checkNotExceed100 method
template
public class Employee {
String name;
int hours;
Employee(String name, int hours) {
this.name = name;
this.hours = hours;
}

// Determines whether the number of hours of work


// exceeds 100
boolean checkNotExceed100() {
...this.name...this.hours...
...this.wage()...this.tax()...
...this.netpay()...this.raisedWage()
}
}

Compound Data - Class 84


checkNotExceed100 method
implement
public class Employee {
String name;
int hours;
Employee(String name, int hours) {
this.name = name;
this.hours = hours;
}
...

// Determines whether the number of hours of work


// exceeds 100
boolean checkNotExceed100() {
return this.hours < 100;
}
}

Compound Data - Class 85


Test checkNotExceed100 method
import junit.framework.*;
public class EmployeeTest extends TestCase {
...
public void testcheckNotExceed100(){
assertTrue(new Employee("Nam", 40).checkNotExceed100());
Employee aEmployee1 = new Employee("Mai", 30);
Employee aEmployee2 = new Employee("Minh", 100);
assertTrue(aEmployee1.checkNotExceed100());
assertFalse(aEmployee2.checkNotExceed100());
}
}

Compound Data - Class 86


Class diagram - Final

Employee
- String name
- int hours

+ int wage()
+ double tax()
+ double netpay()
+ double raisedWage()
+ boolean checkNotExceed100()

Compound Data - Class 87


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.

Compound Data - Class 88


Design Class Method Steps (Contd)
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

Compound Data - Class 89


Exercise 1.5
• Develop the method tax, which consumes the gross
pay and produces the amount of tax owed. For a
gross pay of $240 or less, the tax is 0%; for over
$240 and $480 or less, the tax rate is 15%; and for
any pay over $480, the tax rate is 28%.
• Also develop netpay. The method determines the
net pay of an employee from the number of hours
worked. The net pay is the gross pay minus the tax.
Assume the hourly pay rate is $12

Compound Data - Class 90


Relax…
& Do Exercise

Compound Data - Class 91


Solution exersise 1.5 : taxWithRate()
public double taxWithRate() {
double grossPay = this.wage();
if (grossPay < 240)
return 0.0;
if (grossPay < 480)
return grossPay * 0.15;
return grossPay * 0.28;
}

public void testTaxWithRate() {


assertEquals(new Employee("Nam", 10).taxWithRate(),
0.0, 0.001);
Employee aEmployee1 = new Employee("Mai", 30);
assertEquals(aEmployee1.taxWithRate(), 54.0, 0.001);
Employee aEmployee2 = new Employee("Minh", 100);
assertEquals(aEmployee2.taxWithRate(), 336.0, 0.001);
}
Compound Data - Class 92
Solution exersise 1.5: netpayWithRate()
Method implementation
public double netpayWithRate() {
return this.wage() - this.taxWithRate();
}

Unit testing
public void testNetpayWithRate() {
assertEquals(new Employee("Nam", 10).netpayWithRate(),
120.0, 0.001);
Employee aEmployee1 = new Employee("Mai", 30);
assertEquals(aEmployee1.netpayWithRate(), 306.0, 0.001);
Employee aEmployee2 = new Employee("Minh", 100);
assertEquals(aEmployee2.netpayWithRate(), 864.0, 0.001);
}
Compound Data - Class 93

You might also like