SlideShare a Scribd company logo
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
12
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
Integer type
Name Size Range
Default
value
byte 1 byte -128…127 0
short 2 bytes -32,768…32,767 0
int 4 bytes -2,147,483,648 to
2,147,483,648
0
long 8 bytes -9,223,372,036,854,775,808 to
9,223,372,036,854,775,808
0L
Compound Data - Class 13
14
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
15
Character type
Java represent a Unicode character (2 bytes)
• Q: Distinguish char type and String type ?
• A:
– char c = 't';
– String s = "tin hoc";
Name Size Range Default value
char 2 bytes u0000 … uFFFF u0000
Compound Data - Class 15
16
Boolean type
Name Size Range Default value
boolean 1 byte false, true false
Compound Data - Class 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
Property
or fieldData type
Class Name
CoffeeReceipt
- String kind
- double pricePerPound
- double weight
Method
Compound Data - Class 20
Define Java Class, Constructor
class CoffeeReceipt {
String kind;
double pricePerPound;
double weight;
CoffeeReceipt(String kind,
double pricePerPound, double weight) {
this.kind = kind;
this.pricePerPound = pricePerPound;
this.weight = weight;
}
}
class definition
CONSTRUCTOR
of the class
Field declarations. Each declaration
specifies the type of values that the field
name represents. Accordingly, kind
stands for a String and pricePerPound
and weight are doubles
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 junit.framework.*;
public class CoffeeReceiptTest extends TestCase {
public void testConstructor() {
new CoffeeReceipt("Hawaiian Kona", 15.95, 100);
new CoffeeReceipt("Ethiopian", 8.0, 1000);
new CoffeeReceipt("Colombian Supreme ", 9.5, 1700);
}
}
Import test unit library
Define class CoffeeReceiptTest
is test case.
Test method that name is testXXX
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
Compound Data - Class 25
Date
- int day
- int month
- int year
Define Class, Constructor and Test
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
}
}
class Date {
int day;
int month;
int year;
Date(int day, int month, int year) {
this.day = day;
this.month = month;
this.year = year;
}
}
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
Compound Data - Class 27
GPSLocation
- double latitude
- double longitude
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
Compound Data - Class
Automobile
- String model
- int price [in dollars]
- double mileage [in miles per gallon]
- boolean used
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.
Compound Data - Class
CoffeeReceipt
- String kind
- double pricePerPound
- double weight
??? cost(???)
41
Designs through Templates
• First we add a contract, a purpose statement, and a
header for cost to the CoffeeReceipt class
Compound Data - 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() { ... }
}
Contract is a METHOD SIGNATURE
a purpose statement
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
Compound Data - Class
// to compute the total cost of this coffee purchase
// [in cents]
double cost() {
return 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() {
...this.kind...
...this.pricePerPound...
...this.weight...
}
44
CoffeeReceipt class and method
Compound Data - Class
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;
}
}
45
Test cost method
Compound Data - Class
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);
}
}
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 …
Compound Data - Class 47
CoffeeReceipt
- String kind
- double pricePerPound
- double weight
double cost()
??? priceOver(???)
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.
Compound Data - Class 48
inside of Coffee
// to determine whether this coffee’s price is more
// than amount
boolean priceOver(double amount) { ... }
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
Compound Data - Class
// to determine whether this coffee’s price
// is more than amount
boolean priceOver(int amount) {
return this.pricePerPound > 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) {
... this.kind
... this.pricePerPound
... this.weight
... amount
}
50
Test priceOver method
Compound Data - Class
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));
}
}
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
Compound Data - Class
Posn
- int x
- int y
+ ??? distanceTo0(???)
+ ??? distanceTo(???)
53
Define Class, Constructor, and Test
Compound Data - Class
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);
}
}
54
Computes
How far some pixel is from the origin
• 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
Posn
- int x
- int y
+ ??? distanceToO(???)
+ ??? distanceTo(???)
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...
...this.y...
}
}
Compound Data - Class
Add a contract,
a purpose statement
METHOD SIGNATURE
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
Compound Data - Class
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);
}
}
58
Computes the distance between 2 pixels
• Example
– Distance from A(6, 8) to B(3, 4) is 5
Compound Data - Class
Posn
- int x
- int y
+ double distanceToO()
+ ??? distanceTo(???)
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...
...this.distantoO()...that.distanceToO()...
}
}
Add a contract,
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
Compound Data - Class
Posn
- int x
- int y
+ double distanceToO()
+ double distanceTo(Posn that)
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
Compound Data - Class
Employee
- String name
- int hours
+ ??? wage(???)
+ ??? tax(???)
+ ??? netpay(???)
+ ??? raisedWage(???)
+ ??? checkNotExceed100 (???)
65
Define Class and Contructor and Test
Compound Data - Class
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);
}
}
66
Compute wage
• 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
Employee
- String name
- int hours
+ ??? wage(???)
+ ??? tax(???)
+ ??? netpay(???)
+ ??? raisedWage(???)
+ ??? checkNotExceed100(???)
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
Compound Data - Class
• 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
Employee
- String name
- int hours
+ ??? wage(???)
+ ??? tax(???)
+ ??? netpay(???)
+ ??? raisedWage(???)
+ ??? checkNotExceed100(???)
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
Compound Data - Class
• 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
Employee
- String name
- int hours
+ ??? wage(???)
+ ??? tax(???)
+ ??? netpay(???)
+ ??? raisedWage(???)
+ ??? checkNotExceed100(???)
75
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()...
}
}
netpay method template
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
Compound Data - Class
• 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
Employee
- String name
- int hours
+ ??? wage(???)
+ ??? tax(???)
+ ??? netpay(???)
+ ??? raisedWage(???)
+ ??? checkNotExceed100(???)
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
Compound Data - Class
• 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
Employee
- String name
- int hours
+ ??? wage(???)
+ ??? tax(???)
+ ??? netpay(???)
+ ??? raisedWage(???)
+ ??? checkNotExceed100(???)
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
implementpublic 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
Compound Data - Class
Employee
- String name
- int hours
+ int wage()
+ double tax()
+ double netpay()
+ double raisedWage()
+ boolean checkNotExceed100()
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

More Related Content

PDF
Section2 methods for classes
PDF
Giới thiệu cơ bản về Big Data và các ứng dụng thực tiễn
PDF
báo cáo bài tập lớn phân tích thiết kế hệ thống quản lý khách sạn
PDF
phân tích thiết kế hệ thống thông tin
PDF
TỔNG QUAN VỀ DỮ LIỆU LỚN (BIGDATA)
PDF
Giới thiệu môn học Làm quen với unity3d
PDF
Câu hỏi trắc nghiệm môn kỹ năng ứng dụng công nghệ thông tin có giải...
PDF
Convolutional Neural Networks (CNN) trong Deep Learning.pdf
Section2 methods for classes
Giới thiệu cơ bản về Big Data và các ứng dụng thực tiễn
báo cáo bài tập lớn phân tích thiết kế hệ thống quản lý khách sạn
phân tích thiết kế hệ thống thông tin
TỔNG QUAN VỀ DỮ LIỆU LỚN (BIGDATA)
Giới thiệu môn học Làm quen với unity3d
Câu hỏi trắc nghiệm môn kỹ năng ứng dụng công nghệ thông tin có giải...
Convolutional Neural Networks (CNN) trong Deep Learning.pdf

What's hot (20)

PDF
Tiểu luận Kiến trúc và thiết kế phần mềm PTIT - Software Architecture & Design
PDF
Newtecons - Hội viên VGBC 2020-2021
PDF
Slide bài giảng tổng hợp xác suất thống kê
PDF
BÀI TẬP XÁC SUẤT THỐNG KÊ: PHÂN PHỐI BERNOULLI
PDF
Luận văn: Xây dựng website đa ngôn ngữ cho Công ty, HOT
PDF
Phân tích và thiết kế hệ thống quản lý bán hàng
PPTX
đồ án opencart
PPTX
Slide Đồ Án Tốt Nghiệp Khoa CNTT Web Xem Phim Online Mới
DOC
Báo Cáo Bài Tập Lớn Môn Lập Trình Web Xây Dựng Website Tin Tức
DOCX
Xây dựng hệ thống quản lý cửa hàng bán sách, đĩa nhạc, đĩa phim Media One
PDF
Dm -chapter_1_-_overview_0
PDF
Bảng Student
PDF
Bài tập mẫu C và C++ có giải
PDF
Giáo trình phân tích thiết kế hệ thống thông tin
DOCX
Đề tài: Nhận dạng, phân loại, xử lý ảnh biển số xe bằng phần mềm
PDF
Bài tập HTML/CSS
DOC
Bài giảng thiết kế website - truongkinhtethucpham.com
DOC
Đề tài: Phân tích và thiết kế phần mềm quản lý khách sạn, HAY
PDF
Thiết kế website học trực tuyến e learning
PPT
Chuong01 tổng quan về tmdt
Tiểu luận Kiến trúc và thiết kế phần mềm PTIT - Software Architecture & Design
Newtecons - Hội viên VGBC 2020-2021
Slide bài giảng tổng hợp xác suất thống kê
BÀI TẬP XÁC SUẤT THỐNG KÊ: PHÂN PHỐI BERNOULLI
Luận văn: Xây dựng website đa ngôn ngữ cho Công ty, HOT
Phân tích và thiết kế hệ thống quản lý bán hàng
đồ án opencart
Slide Đồ Án Tốt Nghiệp Khoa CNTT Web Xem Phim Online Mới
Báo Cáo Bài Tập Lớn Môn Lập Trình Web Xây Dựng Website Tin Tức
Xây dựng hệ thống quản lý cửa hàng bán sách, đĩa nhạc, đĩa phim Media One
Dm -chapter_1_-_overview_0
Bảng Student
Bài tập mẫu C và C++ có giải
Giáo trình phân tích thiết kế hệ thống thông tin
Đề tài: Nhận dạng, phân loại, xử lý ảnh biển số xe bằng phần mềm
Bài tập HTML/CSS
Bài giảng thiết kế website - truongkinhtethucpham.com
Đề tài: Phân tích và thiết kế phần mềm quản lý khách sạn, HAY
Thiết kế website học trực tuyến e learning
Chuong01 tổng quan về tmdt
Ad

Similar to Section1 compound data class (20)

PPT
02._Object-Oriented_Programming_Concepts.ppt
PPT
presentation of java fundamental
PDF
Object oriented programming
PDF
PRELIM-Lesson-2.pdf
PPT
Introduction to Java(basic understanding).ppt
PPT
PDF
02-advance-methods-on-class jdpgs code .pdf
PPT
01-introductionto Object ooriented Programming in JAVA CS.ppt
PPT
01-introduction OOPS concepts in C++ JAVA
PDF
Chapter3 bag2
PDF
Section4 union of classes and methods
PPTX
OOPJ.pptx
PDF
Chapter2 bag2
PPTX
UNIT1-JAVA.pptx
PPT
Oops Concept Java
PDF
C How To Program.pdf
PPT
Data Structures: Introduction_______.ppt
PPT
DSA___________________SSSSSSSSSSSSSS.ppt
PDF
M.c.a. (sem iv)- java programming
02._Object-Oriented_Programming_Concepts.ppt
presentation of java fundamental
Object oriented programming
PRELIM-Lesson-2.pdf
Introduction to Java(basic understanding).ppt
02-advance-methods-on-class jdpgs code .pdf
01-introductionto Object ooriented Programming in JAVA CS.ppt
01-introduction OOPS concepts in C++ JAVA
Chapter3 bag2
Section4 union of classes and methods
OOPJ.pptx
Chapter2 bag2
UNIT1-JAVA.pptx
Oops Concept Java
C How To Program.pdf
Data Structures: Introduction_______.ppt
DSA___________________SSSSSSSSSSSSSS.ppt
M.c.a. (sem iv)- java programming
Ad

Recently uploaded (20)

PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PPTX
Cell Types and Its function , kingdom of life
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
RMMM.pdf make it easy to upload and study
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
01-Introduction-to-Information-Management.pdf
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
A systematic review of self-coping strategies used by university students to ...
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Classroom Observation Tools for Teachers
PDF
Complications of Minimal Access Surgery at WLH
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PDF
Trump Administration's workforce development strategy
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
2.FourierTransform-ShortQuestionswithAnswers.pdf
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
Cell Types and Its function , kingdom of life
Module 4: Burden of Disease Tutorial Slides S2 2025
RMMM.pdf make it easy to upload and study
Microbial disease of the cardiovascular and lymphatic systems
01-Introduction-to-Information-Management.pdf
VCE English Exam - Section C Student Revision Booklet
A systematic review of self-coping strategies used by university students to ...
O7-L3 Supply Chain Operations - ICLT Program
Classroom Observation Tools for Teachers
Complications of Minimal Access Surgery at WLH
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
Trump Administration's workforce development strategy

Section1 compound data class

  • 2. 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
  • 3. How To Design program Compound Data - Class 3
  • 4. 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
  • 5. 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
  • 6. 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
  • 7. 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
  • 8. 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
  • 9. 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
  • 10. IDE • IDE: Integrated Development Environment – Netbean: supported by Sun – Eclipse: open source, supported by IBM Compound Data - Class 10
  • 11. The Varieties of Data Compound Data - Class 11
  • 12. 12 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
  • 13. Integer type Name Size Range Default value byte 1 byte -128…127 0 short 2 bytes -32,768…32,767 0 int 4 bytes -2,147,483,648 to 2,147,483,648 0 long 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,808 0L Compound Data - Class 13
  • 14. 14 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
  • 15. 15 Character type Java represent a Unicode character (2 bytes) • Q: Distinguish char type and String type ? • A: – char c = 't'; – String s = "tin hoc"; Name Size Range Default value char 2 bytes u0000 … uFFFF u0000 Compound Data - Class 15
  • 16. 16 Boolean type Name Size Range Default value boolean 1 byte false, true false Compound Data - Class 16
  • 17. 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
  • 18. 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
  • 19. 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
  • 20. Class Diagram: abstractly express Property or fieldData type Class Name CoffeeReceipt - String kind - double pricePerPound - double weight Method Compound Data - Class 20
  • 21. Define Java Class, Constructor class CoffeeReceipt { String kind; double pricePerPound; double weight; CoffeeReceipt(String kind, double pricePerPound, double weight) { this.kind = kind; this.pricePerPound = pricePerPound; this.weight = weight; } } class definition CONSTRUCTOR of the class Field declarations. Each declaration specifies the type of values that the field name represents. Accordingly, kind stands for a String and pricePerPound and weight are doubles Compound Data - Class 21
  • 22. 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
  • 23. 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
  • 24. Test Class import junit.framework.*; public class CoffeeReceiptTest extends TestCase { public void testConstructor() { new CoffeeReceipt("Hawaiian Kona", 15.95, 100); new CoffeeReceipt("Ethiopian", 8.0, 1000); new CoffeeReceipt("Colombian Supreme ", 9.5, 1700); } } Import test unit library Define class CoffeeReceiptTest is test case. Test method that name is testXXX 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
  • 25. 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 Compound Data - Class 25 Date - int day - int month - int year
  • 26. Define Class, Constructor and Test 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 } } class Date { int day; int month; int year; Date(int day, int month, int year) { this.day = day; this.month = month; this.year = year; } } Compound Data - Class 26
  • 27. 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 Compound Data - Class 27 GPSLocation - double latitude - double longitude
  • 28. 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
  • 29. 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
  • 30. 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
  • 31. 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
  • 32. Exercise 1.3 • Translate the class diagram in figure into a class definition. Also create instances of the class Compound Data - Class Automobile - String model - int price [in dollars] - double mileage [in miles per gallon] - boolean used 32
  • 33. 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
  • 35. 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
  • 36. 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
  • 37. 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
  • 38. 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
  • 39. 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
  • 40. 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
  • 41. 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. Compound Data - Class CoffeeReceipt - String kind - double pricePerPound - double weight ??? cost(???) 41
  • 42. Designs through Templates • First we add a contract, a purpose statement, and a header for cost to the CoffeeReceipt class Compound Data - 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() { ... } } Contract is a METHOD SIGNATURE a purpose statement 42
  • 43. 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
  • 44. cost method template and result Compound Data - Class // to compute the total cost of this coffee purchase // [in cents] double cost() { return 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() { ...this.kind... ...this.pricePerPound... ...this.weight... } 44
  • 45. CoffeeReceipt class and method Compound Data - Class 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; } } 45
  • 46. Test cost method Compound Data - Class 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); } } 46
  • 47. 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 … Compound Data - Class 47 CoffeeReceipt - String kind - double pricePerPound - double weight double cost() ??? priceOver(???)
  • 48. 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. Compound Data - Class 48 inside of Coffee // to determine whether this coffee’s price is more // than amount boolean priceOver(double amount) { ... }
  • 49. 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
  • 50. priceOver method template and result Compound Data - Class // to determine whether this coffee’s price // is more than amount boolean priceOver(int amount) { return this.pricePerPound > 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) { ... this.kind ... this.pricePerPound ... this.weight ... amount } 50
  • 51. Test priceOver method Compound Data - Class 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)); } } 51
  • 52. 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
  • 53. Class diagram Compound Data - Class Posn - int x - int y + ??? distanceTo0(???) + ??? distanceTo(???) 53
  • 54. Define Class, Constructor, and Test Compound Data - Class 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); } } 54
  • 55. Computes How far some pixel is from the origin • 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 Posn - int x - int y + ??? distanceToO(???) + ??? distanceTo(???) Compound Data - Class 55
  • 56. 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... ...this.y... } } Compound Data - Class Add a contract, a purpose statement METHOD SIGNATURE 56
  • 57. 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
  • 58. Test distanceToO method Compound Data - Class 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); } } 58
  • 59. Computes the distance between 2 pixels • Example – Distance from A(6, 8) to B(3, 4) is 5 Compound Data - Class Posn - int x - int y + double distanceToO() + ??? distanceTo(???) 59
  • 60. 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... ...this.distantoO()...that.distanceToO()... } } Add a contract, a purpose statement METHOD SIGNATURE Compound Data - Class 60
  • 61. 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
  • 62. 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
  • 63. Class diagram - Final Compound Data - Class Posn - int x - int y + double distanceToO() + double distanceTo(Posn that) 63
  • 64. 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
  • 65. Class diagram Compound Data - Class Employee - String name - int hours + ??? wage(???) + ??? tax(???) + ??? netpay(???) + ??? raisedWage(???) + ??? checkNotExceed100 (???) 65
  • 66. Define Class and Contructor and Test Compound Data - Class 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); } } 66
  • 67. Compute wage • 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 Employee - String name - int hours + ??? wage(???) + ??? tax(???) + ??? netpay(???) + ??? raisedWage(???) + ??? checkNotExceed100(???) 67
  • 68. 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
  • 69. 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
  • 70. 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
  • 71. Compute tax Compound Data - Class • 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 Employee - String name - int hours + ??? wage(???) + ??? tax(???) + ??? netpay(???) + ??? raisedWage(???) + ??? checkNotExceed100(???) 71
  • 72. 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
  • 73. 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
  • 74. 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
  • 75. Class diagram Compound Data - Class • 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 Employee - String name - int hours + ??? wage(???) + ??? tax(???) + ??? netpay(???) + ??? raisedWage(???) + ??? checkNotExceed100(???) 75
  • 76. 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()... } } netpay method template Compound Data - Class 76
  • 77. 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
  • 78. 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
  • 79. Class diagram Compound Data - Class • 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 Employee - String name - int hours + ??? wage(???) + ??? tax(???) + ??? netpay(???) + ??? raisedWage(???) + ??? checkNotExceed100(???) 79
  • 80. 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
  • 81. 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
  • 82. 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
  • 83. Class diagram Compound Data - Class • 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 Employee - String name - int hours + ??? wage(???) + ??? tax(???) + ??? netpay(???) + ??? raisedWage(???) + ??? checkNotExceed100(???) 83
  • 84. 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
  • 85. checkNotExceed100 method implementpublic 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
  • 86. 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
  • 87. Class diagram - Final Compound Data - Class Employee - String name - int hours + int wage() + double tax() + double netpay() + double raisedWage() + boolean checkNotExceed100() 87
  • 88. 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
  • 89. 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
  • 90. 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
  • 92. 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
  • 93. 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