SlideShare a Scribd company logo
1 of 135
Download to read offline
Unions of Classes and
Methods
1
The Drawing Program
• Develop a drawing program that deals with at least three
kinds of shapes: dots, squares, and circles.
The shapes are located on a Cartesian grid whose origin
is in the northwest.
– A dot is located in the grid and is drawn as a small disk of a fixed
size (3 pixels).
– A square's location is specified via its north-west corner in the
grid and its size.
– A circle's essential properties are its center point and its radius.
2
Class diagram
3
• IShape is the name for a union of variant classes; it is special
because it doesn’t contribute any objects to the complete
collection. Its sole purpose is to represent the complete
collection of object
IShape
Dot
- CartPt location
Square
- CartPt location
- int size
Circle
- CartPt location
- int radius
CartPt
- int x
- int y
AShape is one of a Dot,
a Square, a Circle
Express the relationship
between these classes,
so that IShape as types of data
Class diagram
4
• The AShape class is SUPERCLASS. Dot, Square, and Circle are
SUBCLASSES, or REFINES Ashape, or is DERIVED from AShape.
• Because all instances of AShape are instances of either Dot, Square, or
Circle, we say that AShape is an ABSTRACT CLASS
AShape
Dot
- CartPt location
Square
- CartPt location
- int size
Circle
- CartPt location
- int radius
CartPt
- int x
- int y
AShape is one of a Dot,
a Square, a Circle
Express the relationship
between these classes,
so that AShape as types of data
Java data definitions
5
public class CartPt {
private int x;
private int y;
public CartPt(int x, int y) {
this.x = x;
this.y = y;
}
}
Java data definitions
6
public interface IShape {
}
public class Dot implements IShape {
private CartPt location;
public Dot(CartPt location) {
this.location = location;
}
} public class Square implements IShape {
private CartPt location;
private int size;
public Square(CartPt location, int size) {
this.location = location;
this.size = size;
}
} public class Circle implements IShape {
private CartPt location;
private int radius;
public Circle(CartPt location, int radius) {
this.location = location;
this.radius = radius;
}
}
Test constructors
7
public class ShapeTest extends TestCase {
public void testConstructor() {
//test for class CartPt
CartPt caPt1 = new CartPt(4, 3);
CartPt caPt2 = new CartPt(5, 12);
CartPt caPt3 = new CartPt(6, 8);
// test for class Dot
IShape d1 = new Dot(caPt1);
IShape d2 = new Dot(caPt2);
IShape d3 = new Dot(caPt3);
//test for class Circle
IShape c1 = new Circle(caPt1, 5);
IShape c2 = new Circle(caPt2, 10);
IShape c3 = new Circle(caPt3, 12);
//test for class Square
IShape s1 = new Square(caPt1,5);
IShape s2 = new Square(caPt3,10);
IShape s3 = new Square(caPt3,12);
}
}
Zoo example
8
Zoo example
• Develop a program that helps a zoo keeper take care of
the animals in the zoo.
• For now the zoo has lions, snakes, and monkeys. Every
animal has a name and weight. The zoo keeper also
needs to know how much meat the lion eats per day, the
length of each snake, and the favorite food for each
monkey
• Examples:
– The lion Leo weighs 300 pounds and eats 5 pounds of meat
every day;
– The snake Boa weighs 50 pounds and is 5 feet long;
– The monkey George weighs 150 poundds and loves bananas.
– The monkey Mina weighs 120 pounds and loves to eat kiwi
9
Class diagram
10
IZooAnimal
Lion
-String name
-int weight
-int meat
Snake
-String name
-int weight
-int lenght
Monkey
-String name
-int weight
-String food
11
public interface IZooAnimal{
}
public class Lion implements IZooAnimal{
private String name;
private int weight;
private int meat;
public Lion(String name, int weight, int meat) {
this.name = name;
this.weight = weight;
this.meat = meat;
}
}
public class Snake implements IZooAnimal{
private String name;
private int weight;
private int length;
public Snake(String name, int weight, int length) {
this.name = name;
this.weight = weight;
this.length = length;
}
}
public class Monkey implements IZooAnimal{
private String name;
private int weight;
private String food;
public Monkey(String name, int weight, String food) {
this.name = name;
this.weight = weight;
this.food = food;
}
}
Java definitions
Test constructor
12
public class AnimalTest extends TestCase {
public void testConstructor(){
// test for class Lion
IZooAnimal leo = new Lion("Leo", 300, 5);
IZooAnimal samba = new Lion("Samba", 200, 3);
IZooAnimal Cleopon = new Lion("Cleopon", 250, 5);
// test for class Snake
IZooAnimal boa = new Snake("Boa", 50,5);
IZooAnimal mic = new Snake("Mic", 45,4);
IZooAnimal bu = new Snake("Bu", 55,6);
// test for class Monkey
IZooAnimal george = new Monkey("George", 150, "banana");
IZooAnimal mina = new Monkey("Mina", 120, "Kiwi");
IZooAnimal slan = new Monkey("Slan", 100, "Kiwi");
}
}
Common Data
• Notice that, three subclasses have one thing in common,
namely, a location.
That is, each dot, square, or circle has a location.
• Subclasses have the commonalities and the differences.
– tend to attribute the commonalities to the superclass, and the
differences to the subclasses.
13
Dot Square
- int size
Circle
- int radius
AShape
# CartPt location
CartPt
- int x
- int y
Subclasses inherits the location
field from Ashape superclass
Java data definitions
14
public abstract class AShape {
protected CartPt location;
}
public class Dot extends AShape {
}
public class Square extends AShape {
private int size;
}
public class Circle extends AShape {
private int radius;
}
Contructor of AShape
15
Two constructor
format of Square
public abstract class AShape {
protected CartPt location;
protected Ashape(CartPt location) {
this.location = location;
}
}
public abstract class AShape {
protected CartPt location;
} public class Square extends AShape {
private int size;
public Square(CartPt location, int size) {
this.location = location;
this.size = size;
}
}
public class Square extends AShape {
private int size;
public Square(CartPt location, int size) {
super(location);
this.size = size;
}
}
access protected
location field
inherits form AShape
call constructor of
Ashape superclass
Final Java data definitions (format 1)
16
public abstract class AShape {
protected CartPt location;
}
public class Dot extends AShape {
public Dot(CartPt location) {
this.location = location;
}
} public class Square extends AShape {
private int size;
public Square(CartPt location, int size) {
this.location = location;
this.size = size;
}
} public class Circle extends AShape {
private int radius;
public Circle(CartPt location, int radius) {
this.location = location;
this.radius = radius;
}
}
Subclasses can access
protected location
common field inherits
form AShape
Final Java data definitions (format 2)
17
public abstract class AShape {
protected CartPt location;
protected Ashape(CartPt location) {
this.location = location;
}
} public class Dot extends AShape {
public Dot(CartPt location) {
super(location);
}
} public class Square extends AShape {
private int size;
public Square(CartPt location, int size) {
super(location);
this.size = size;
}
} public class Circle extends AShape {
private int radius;
public Circle(CartPt location, int radius) {
super(location);
this.radius = radius;
}
}
Subclasses call
constructor of Ashape
superclass
Keyword
• abstract in front of a class indicates
– The class is abstract.
– there are no instances of this class.
• can not use new operator to create an object of this
class.
• extends
– makes the Dot class a refinement or an extension of
AShape therefore INHERITS all of AShape's fields.
18
protected attribute and method
• protected: the class itself and its subclass
can access this attribute / method.
• Q: Review public and private modifiers for
attribute and method.
– public: Classes in all packages can see this attribute
and method.
– private: the class itself can access this attribute /
method.
– None modifier: Classes in the same package can
access attribute and method.
19
Modifiers for class
• None modifier: Classes in the same package
can see this class.
• public: Classes in all packages can see this
class.
20
Test constructors
21
public class ShapeTest extends TestCase {
public void testConstructor() {
//test for class CartPt
CartPt caPt1 = new CartPt(4, 3);
CartPt caPt2 = new CartPt(5, 12);
CartPt caPt3 = new CartPt(6, 8);
// test for class Dot
AShape d1 = new Dot(caPt1);
AShape d2 = new Dot(caPt2);
AShape d3 = new Dot(caPt3);
//test for class Circle
AShape c1 = new Circle(caPt1, 5);
AShape c2 = new Circle(caPt2, 10);
AShape c3 = new Circle(caPt3, 12);
//test for class Square
AShape s1 = new Square(caPt1,5);
AShape s2 = new Square(caPt3,10);
AShape s3 = new Square(caPt3,12);
}
}
Types vs Classes
• A type describes for what kind of objects a variable or a
parameter
• In Java, a type is either the name of an interface, a
class, or a primitive type (int, double, boolean or
String).
• When we write:
AShape s;
– s has type AShape
– which means that it is a placeholder for some unknown shape.
• Similarly, when we introduce an example such as
AShape s = new Square(...)
– s has type AShape, even though we know that it stands for an
instance of Square.
22
Zoo example
23
Zoo example
• Develop a program that helps a zoo keeper take care of
the animals in the zoo.
• For now the zoo has lions, snakes, and monkeys. Every
animal has a name and weight. The zoo keeper also
needs to know how much meat the lion eats per day, the
length of each snake, and the favorite food for each
monkey
• Examples:
– The lion Leo weighs 300 pounds and eats 5 pounds of meat
every day;
– The snake Boa weighs 50 pounds and is 5 feet long;
– The monkey George weighs 150 poundds and loves bananas.
– The monkey Mina weighs 120 pounds and loves to eat kiwi
24
Class diagram
25
Animal
# String name
# int weight
Lion
- int meat
Snake
- int lenght
Monkey
- String food
26
public abstract class Animal {
protected String name;
protected int weight;
}
public class Lion extends Animal {
private int meat;
public Lion(String name, int weight, int meat) {
this.name = name;
this.weight = weight;
this.meat = meat;
}
}
public class Snake extends Animal {
private int length;
public Snake(String name, int weight, int length) {
this.name = name;
this.weight = weight;
this.length = length;
}
}
public class Monkey extends Animal {
private String food;
public Monkey(String name, int weight, String food) {
this.name = name;
this.weight = weight;
this.food = food;
}
}
Java definitions
27
public abstract class Animal {
protected String name;
protected int weight;
protected Animal(String name, int weight) {
this.name = name;
this.weight = weight;
}
} public class Lion extends Animal {
private int meat;
public Lion(String name, int weight, int meat) {
super(name, weight);
this.meat = meat;
}
} public class Snake extends Animal {
private int length;
public Snake(String name, int weight, int length) {
super(name, weight);
this.length = length;
}
} public class Monkey extends Animal {
private String food;
public Monkey(String name, int weight, String food) {
super(name, weight);
this.food = food;
}
}
Java definitions
Subclasses call a
contructor of super
class
Test constructor
28
public class AnimalTest extends TestCase {
public void testConstructor(){
// test for class Lion
Animal leo = new Lion("Leo", 300, 5);
Animal samba = new Lion("Samba", 200, 3);
Animal cleopon = new Lion("Cleopon", 250, 5);
// test for class Snake
Animal boa = new Snake("Boa", 50,5);
Animal mic = new Snake("Mic", 45,4);
Animal bu = new Snake("Bu", 55,6);
// test for class Monkey
Animal george = new Monkey("George", 150, "banana");
Animal mina = new Monkey("Mina", 120, "Kiwi");
Animal slan = new Monkey("Slan", 100, "Kiwi");
}
}
“this” and “super” keyword
• this: references to instance itself.
• super: references to superclass.
29
Exercises
Part I: Exercise 4.1.1 to 4.1.4 (HTDCH)
Do in class 4.1.1
30
Exercise 4.1.1
Design a data representation for this problem:
. . . Develop a “bank account” program. The program keeps track
of the balances in a person’s bank accounts. Each account has
an id number and a customer’s name. There are three kinds of
accounts: a checking account, a savings account, and a
certificate of deposit (CD). Checking account information also
includes the minimum balance. Savings account includes the
interest rate. A CD specifies the interest rate and the maturity
date. Naturally, all three types come with a current balance. . . .
• Represent the following examples using your classes:
– 1. Earl Gray, id# 1729, has $1,250 in a checking account with
minimum balance of $500;
– 2. Ima Flatt, id# 4104, has $10,123 in a certificate of deposit whose
interest rate is 4% and whose maturity date is June 1, 2005;
– 3. Annie Proulx, id# 2992, has $800 in a savings account; the
account yields interest at the rate of 3.5%.
31
Exercise 4.1.2
• Develop a program that creates a gallery from three
different kinds of records: images (gif), texts (txt), and
sounds (mp3). All have names for source files and sizes
(number of bytes). Images also include information about
the height, the width, and the quality of the image. Texts
specify the number of lines needed for visual
representation. Sounds include information about the
playing time of the recording, given in seconds.
• Examples:
– an image, stored in flower.gif; size: 57,234 bytes; width: 100
pixels; height: 50 pixels; quality: medium;
– a text, stored in welcome.txt; size: 5,312 bytes; 830 lines;
– a music piece, stored in theme.mp3; size: 40960 bytes, playing
time 3 minutes and 20 seconds.
32
Extended exercises
• Exercise 7.2.2 (HTDP). The administrators of
metropolitan transportation agencies manage
fleets of vehicles. Develop data definitions for a
collection of such vehicles. The collection should
include at least buses, limos, cars, and subways.
Add at least two attributes per class of vehicle.
33
Relax &
…Do Exercises …
34
Design methods for unions
of classes
35
Recall the Drawing Program
36
Dot Square
- int size
Circle
- int radius
AShape
# CartPt location
CartPt
- int x
- int y
11
Requirements
1. Compute the area of a shape
2. Compute the distance of a shape to the origin
3. Determine whether some point is inside the shape
4. Compute the bounding box of a shape
• All of these methods clearly work with shapes in general
but may have to compute different results depending on
the concrete shape on which they are invoked
– For example, a Dot has no true area; a Square's area is
computed differently from a Circle's area
• In an object-oriented language, we can indicate that all
AShape's have such method with ABSTRACT methods
37
Add method for union
38
Add method for Shape
39
Dot Square
- int size
Circle
- int radius
AShape
# CartPt location
CartPt
- int x
- int y
11
??? mmm()
??? mmm()
??? mmm() ??? mmm()
??? kkk()
1. Computing Area of A Shape
40
Augmenting Ashape
area() purpose and signature
public abstract class AShape {
protected CartPt location;
protected AShape(CartPt location) {
this.location = location;
}
// compute area of AShape
public abstract double area();
}
41
Q: Create a method template for each of the subclasses of AShape
Abstract Methods
• An abstract method isn't a method;
it is just a method signature preceded with the
keyword abstract
• An abstract method must be defined in an
abstract class,
and announces that the concrete subclasses
have CONCRETE METHODS with the same
signature and a proper method body
42
Template for area() of Dot
43
Tips: a class extends other class, it inherits all fields of this class such
as Circle, Square,Dot extends AShape so that it inherit field "location"
of AShape class.
public class Dot extends AShape {
public Dot(CartPt location) {
super(location);
}
public double area() {
...this.location...
}
}
Template for area() of Square
44
public class Square extends AShape {
private int size;
public Square(CartPt location, int size) {
super(location);
this.size = size;
}
public double area() {
...this.location...
...this.size...
}
}
Template for area() of Circle
45
Q: Do the Example step
public class Circle extends AShape {
private int radius;
public Circle(CartPt location, int radius) {
super(location);
this.radius = radius;
}
public double area() {
...this.location...
...this.radius...
}
}
Add method to class diagram
46
Dot
+ double area()
Square
- int size
+ double area()
Circle
- int radius
+ double area()
AShape
# CartPt location
+ double area()
CartPt
- int x
- int y
Examples
• new Dot(new CartPt(4, 3)).area()
// should be 0.0
• new Square(new CartPt(4, 3), 30).area()
// should be 900.0
• new Circle(new CartPt(5, 5), 20).area()
// should be 1256.6...
47
Q: Implement the body of all area() methods
Implement area() method
48
// inside of Dot
public double area() {
return 0.0;
}
// inside of Circle
public double area() {
return Math.PI * this.radius * this.radius;
}
// inside of Square
public double area() {
return this.size * this.size;
}
Unit Testing
49
public class AShapeTest extends TestCase {
public void testArea() {
assertEquals(new Dot(new CartPt(4, 3))
.area(), 0.0, 0.01);
assertEquals(new Square(new CartPt(4, 3), 30)
.area(), 900, 0.01);
assertEquals(new Circle(new CartPt(5, 5), 20)
.area(), 1256.64, 0.01);
}
}
Polymorphism
• With the same call area(), but each concrete
subclass deal with it in difference way.
50
Polymorphism
2. Computing the distance of a
shape to the origin
51
Distance of a shape to the origin
What is the distance between a shape and the
origin?
52
X
Y
0
distanceToO() purpose and signature
53
public abstract class AShape {
protected CartPt location;
protected AShape(CartPt location) {
this.location = location;
}
public abstract double area();
// to compute the distance of this shape
// to the origin
public abstract double distanceToO();
}
Same implement distanceToO()
54
// inside of Dot
public double distanceToO() {
return this.location.distanceToO();
}
// inside of Circle
public double distanceToO() {
return this.location.distanceToO();
}
// inside of Square
public double distanceToO() {
return this.location.distanceToO();
}
Extracting Common Methods to Subclasses
• Q: Is there any difference in the implementations
of distanceToO() in all the subclasses
• A: No, there is no difference at all
• To remove similarities, we could pull
distanceToO() up to the superclass AShape
55
Pull distanceToO() up to AShape
56
public abstract class AShape {
protected CartPt location;
public abstract double area();
public double distanceToO() {
return this.location.distanceToO();
}
}
public class CartPt {
private int x;
private int y;
public double distanceToO() {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
}
Unit Test
57
public void testDistanceToO() {
assertEquals(new Dot(new CartPt(4, 3))
.distanceToO(), 5.0, 0.001);
assertEquals(new Square(new CartPt(4, 3), 30)
.distanceToO(), 5.0, 0.001);
assertEquals(new Circle(new CartPt(12, 5), 20)
.distanceToO(), 13.0, 0.001);
}
Class diagram
58
Dot
+ double area()
Square
- int size
+ double area()
Circle
- int radius
+ double area()
AShape
# CartPt location
+ double area()
+ double distanceToO()
CartPt
- int x
- int y
+ double distanceToO()
3. Determining whether some point is
inside the shape
59
Is point inside the shape
A given point is inside a DOT when its distance
to this DOT is 0.
a given point is inside a CIRCLE if its distance to
the center of the CIRCLE is less than or equal
the radius.
A given point is inside a SQUARE when it is
between two pairs of lines.
60
contains() purpose and signature
61
Q: Create a method template for each of the subclasses of AShape
and do the Example step
public abstract class AShape {
protected CartPt location;
protected AShape(CartPt location) {
this.location = location;
}
public double distanceToO() {
return this.location.distanceToO();
}
public abstract double area();
// is the given point is within the bounds of this shape
public abstract boolean contains(CartPt point);
}
Examples
• new Dot(new CartPt(100, 200))
.contains(new CartPt(100, 200)) // should be true
• new Dot(new CartPt(100, 200))
.contains(new CartPt(80, 220)) // should be false
• new Square(new CartPt(100, 200), 40)
.contains(new CartPt(120, 220)) // should be true
• new Square(new CartPt(100, 200), 40)
.contains(new CartPt(80, 220)) // should be false
• new Circle(new CartPt(0, 0),20)
.contains(new CartPt(4, 3)) // should be true
• new Circle(new CartPt(0, 0), 10)
.contains(new CartPt(12, 5)) // should be false
62
Domain Knowledge
• How to determine whether some point is inside
the shape is a kind of knowledge called
DOMAIN KNOWLEDGE
• To comprehend the domain knowledge, we
sometimes look up in a book and in other
situations we gather from experts
63
Implement contains()
64
// inside of Dot
public boolean contains(CartPt point) {
return this.location.distanceTo(point) == 0.0;
}
// inside of Circle
public boolean contains(CartPt point) {
return this.location.distanceTo(point) <= this.radius;
}
distanceTo() in CartPt
65
public class CartPt {
private int x;
private int y;
public CartPt(int x, int y) {
this.x = x;
this.y = y;
}
public double distanceToO() {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
// compute distance of this point to another point
public double distanceTo(CartPt that) {
double diffX = this.x - that.x;
double diffY = this.y - that.y;
return Math.sqrt(diffX * diffX + diffY * diffY);
}
}
Implement contains() in Square
66
size
size
x + size
y + size
location
O
x
y
67
// inside of Square
public boolean contains(CartPt point) {
int thisX = this.location.getX();
int thisY = this.location.getY();
return this.between(point.getX(), thisX, thisX + this.size)
&& this.between(point.getY(), thisY, thisY + this.size);
}
//-----------------------------------------------------------
private boolean between(int value, int low, int high) {
return (low <= value) && (value <= high);
}
// inside of CartPt
public class CartPt {
private int x;
private int y;
public int getX() { return this.x; }
public int getY() { return this.y; }
}
Unit test
68
public void testContain(){
assertTrue(new Dot(new CartPt(100, 200))
.contains(new CartPt(100, 200)));
assertFalse(new Dot(new CartPt(100, 200))
.contains(new CartPt(80, 220)));
assertTrue(new Square(new CartPt(100, 200),40)
.contains(new CartPt(120, 220)));
assertFalse(new Square(new CartPt(100, 200),40)
.contains(new CartPt(80, 220)));
assertTrue(new Circle(new CartPt(0, 0),20)
.contains(new CartPt(4, 3)));
assertFalse(new Circle(new CartPt(0, 0),10)
.contains(new CartPt(12, 5)));
}
Class diagram
69
Dot
+ double area()
+ boolean contains(CartPt point)
Square
- int size
+ double area()
+ boolean contains(CartPt point)
Circle
- int radius
+ double area()
+ boolean contains(CartPt point)
AShape
# CartPt location
+ double area()
+ double distanceToO()
+ boolean contains(CartPt point)
CartPt
- int x
- int y
+ double distanceToO()
+ double distanceTo(CartPt that)
4. Computing the bounding box of a
shape
70
What is a Bounding Box?
• A bounding box is the smallest square that
completely surrounds the given shape
– The bounding box for a Square is the given square itself.
– For a Circle, the bounding box is also a square,
• its width and height are 2 * radius and
• its northwest corner is one radius removed from the center of
the circle in both directions.
– The bounding box for a Dot is a square with no extent.
Mathematicians call this idea a special case
71
Q: Add the boundingBox() method to AShape
Class diagram
72
Dot
+ double area()
+ boolean contains(CartPt point)
+ Square boundingBox()
Square
- int size
+ double area()
+ boolean contains(CartPt point)
+ Square boundingBox()
Circle
- int radius
+ double area()
+ boolean contains(CartPt point)
+ Square boundingBox()
AShape
# CartPt location
+ double area()
+ double distanceToO()
+ boolean contains(CartPt point)
+ Square boundingBox()
CartPt
- int x
- int y
+ double distanceToO()
+ double distanceTo(CartPt that)
boundingBox purpose and signature
73
public abstract class AShape {
protected CartPt location;
protected AShape(CartPt location) {
this.location = location;
}
public double distanceToO() {
return this.location.distanceToO();
}
public abstract double area();
public abstract boolean contains(CartPt point);
// compute the bounding box for this shape
public abstract Square boundingBox();
}
Examples
74
new Dot(new CartPt(100, 100)).boundingBox()
// should be
new Square(new CartPt(100, 100), 0)
new Square(new CartPt(100, 100), 40).boundingBox()
// should be
new Square(new CartPt(100, 100), 40)
new Circle(new CartPt(0, 0), 20).boundingBox()
// should be
new Square(new CartPt(-20, -20), 40)
Implement boundingBox() method
75
// inside of Square
public Square boundingBox() {
return new Square(this.location, this.size);
}
// inside of Dot
public Square boundingBox() {
return new Square(this.location, 0);
}
boundingBox method in Circle
76
public Square boundingBox() {
return new Square(this.location.translate(
-this.radius, -this.radius), this.radius * 2);
}
// inside of CartPt
// translate this point to deltaX, deltaY distance
public CartPt translate(int deltaX, int deltaY) {
return new CartPt(this.x + deltaX, this.y + deltaY);
}
Unit test
77
public void testBoudingBox(){
assertTrue(new Dot(new CartPt(4, 3)).boundingBox()
.equals(new Square(new CartPt(4, 3), 0)));
assertTrue(new Circle(new CartPt(5, 5), 5).boundingBox()
.equals(new Square(new CartPt(0, 0), 10)));
assertTrue(new Square(new CartPt(4, 3), 30).boundingBox()
.equals(new Square(new CartPt(4, 3), 30)));
}
equals method
78
// inside of Square class
public boolean equals(Object obj) {
if (null==obj || !(obj instanceof Square))
return false;
else {
Square that = (Square) obj;
return (this.location.equals(that.location)
&& this.size == that.size);
}
}
// inside of CartPt class
public boolean equals(Object obj) {
if (null==obj || !(obj instanceof CartPt))
return false;
else {
CartPt that = (CartPt) obj;
return (this.x == that.x) && (this.y == that.y);
}
}
Overriding method
• The supper class and suclass have the same
method (same name and same parameters,
same return data type).
• Method in subclass disables method in supper
class.
79
“Overiding” or “Overloading”
• All classes in Java extends Object class
• Q: distinguish “overloading” and “overriding” ?
• A:
– Method equals(Object) in class Square is called
overriding method equals(Object) in class Object.
– Method area() and area(Cirlce) in class Cirlce
have the same name but different parameter is called
overloading.
• When we invoke overloading methods, the method with
appropriate argument will do
80
A Summary of Important Points
1. How helpful the template-directed design is
2. The refinement arrows let us know where to
place abstract methods and concrete methods
3. The containment arrow reminds us that we can
place auxiliary methods in those classes so that
each object performs the appropriate method
calculations in the end.
81
Exercises
82
Exercise 5.0.4
• Draw a class diagram for the classes in the
shape hierarchy
83
CartPt
- int x
- int y
+ int getX()
+ int getY()
+ double distanceToO()
+ double distanceTo(CartPt that)
+ void translate(int dx, int dy)
AShape
# CartPt location
# AShape(CartPt location)
+ double distanceToO()
+ double area()
+ boolean contains(CartPt point)
+ Square boundingBox()
1
Dot Square
- int size
- boolean between(int value, int low, int high)
Circle
- int radius
Exercise 5.0.5
• Design an extension for the class hierarchy of
shapes that deals with Rectangles. The
extension should cope with all the abstract
methods in AShape
84
Solution 5.0.5
85
Q: Both Square and Rectangle do need the method between().
Remove similarities in these two classes
A: Since between() could exist independently, that it does not need to
belong to any of the existing classes, it could be put in a helping class
CartPt
- int x
- int y
+ int getX()
+ int getY()
+ double distanceToO()
+ double distanceTo(CartPt that)
+ void translate(int dx, int dy)
AShape
# CartPt location
# AShape(CartPt location)
+ double distanceToO()
+ double area()
+ boolean contains(CartPt point)
+ Rectangle boundingBox()
11
Dot Square
- int size
Circle
- int radius
Rectangle
- int width
- int height
Solution 5.0.5: Improved Design
86
CartPt
- int x
- int y
+ int getX()
+ int getY()
+ double distanceToO()
+ double distanceTo(CartPt that)
+ void translate(int dx, int dy)
AShape
# CartPt location
# AShape(CartPt location)
+ double distanceToO()
+ double area()
+ boolean contains(CartPt point)
+ Rectangle boundingBox()
11
Dot Square
- int size
Circle
- int radius
Rectangle
- int width
- int height
ShapeUtils
<<static>> + boolean between(int value, int low, int high)
uses
uses
Solution 5.0.5: ShapeUtils
87
public class ShapeUtils {
public static boolean between(int value, int low,
int high) {
return (low <= value) && (value <= high);
}
}
static modifier for attribute and method
• static: classes can access this attribute/
method without create an instance of class
which contains it.
88
Solution 5.0.5: Rectangle
89
public class Rectangle extends AShape {
private int width;
private int height;
public Rectangle(CartPt location,
int width, int height) { … }
public double area() {
return this.width * this.height;
}
public boolean contains(CartPt point) {
int thisX = this.location.getX();
int thisY = this.location.getY();
return
ShapeUtils.between(point.getX(), thisX, thisX + this.width)
&& ShapeUtils.between(point.getY(), thisY, thisY + this.height);
}
public Rectangle boundingBox() {
return new Rectangle(this.location, width, height);
}
}
Exercise 5.0.6
• Design an extension for the class hierarchy of
shapes so that a program can request the length
of the perimeter for each shape in the hierarchy
90
Solution 5.0.6
91
CartPt
- int x
- int y
+ int getX()
+ int getY()
+ double distanceToO()
+ double distanceTo(CartPt that)
+ void translate(int dx, int dy)
AShape
# CartPt location
# AShape(CartPt location)
+ double distanceToO()
+ double area()
+ boolean contains(CartPt point)
+ Rectangle boundingBox()
+ double perimeter()
11
Dot Square
- int size
Circle
- int radius
Rectangle
- int width
- int height
ShapeUtils
<<static>> + boolean between(int left, int mid, int right)
uses
uses
Solution 5.0.6 (cont.)
92
// in Dot
public double perimeter() {
return 1.0;
}
// in Square
public double perimeter() {
return this.size * 4;
}
// in Rectangle
public double perimeter() {
return (this.width + this.height) * 2;
}
// in Circle
public double perimeter() {
return this.radius * 2 * Math.PI;
}
Extended exercise
• Compute the bounding box the class hierarchy
of shapes that deals with Rectangles. The
extension should cope with all the abstract
methods in AShape
• This is a very interesting exercise !
93
Relax &
…Do Exercises …
94
The Fuel Consumption Problem
95
Problem Statement
• A school district needs to manage the fuel
consumption for its fleet of vehicles, which
includes school busses, cars, and trucks.
Each vehicle has a fuel tank of some size (in
gallons). The district also knows the average
mile-per-gallon consumption of fuel per vehicle.
The fuel consumption for cars and busses
depends on the number of passengers the
vehicle carries; the fuel consumption of a truck
increases with its load (in tons)
96
Class Diagram
97
AVehicle
- double fuelTankVolume // in gallons
- double averageMilePerGallon
Bus
- int nPassengers
Car
- int nPassengers
Truck
- double loadInTons
Examples
98
Car c1 = new Car(15.0, 25.0, 1);
Truck t1 = new Truck(120., 6.0, 0.5);
Bus b1 = new Bus(60.0, 10.0, 20);
Requirement
• The manager needs to know how much it costs
to refuel a vehicle with empty fuel tank at the
current fuel prices so that the district can create
estimates for the gas budget
• Q: Improve the current class diagram and give
more examples
99
Improved Class Diagram
100
AVehicle
- double fuelTankVolume // in gallons
- double averageMilePerGallon
+ double refuelCost(double costPerGallon)
Bus
- int nPassengers
Car
- int nPassengers
Truck
- double loadInTons
More Examples
101
Bus b1 = new Bus(60.0, 10.0, 20);
Car c1 = new Car(15.0, 25.0, 1);
Truck t1 = new Truck(120., 6.0, 0.5);
b1.refuelCost(2.00)
// should be 120.0
c1.refuelCost(2.00)
// should be 30.0
t1.refuelCost(2.00)
// should be 240.0
Implementation of refuelCost()
• Since three subclasses have the same
implementation for refuelCost(), we could
move this method to the parent class. This
means refuelCost() now in the AVehicle
class will not be abstract any more
102
public double refuelCost(double costPerGallon) {
return costPerGallon * this.fuelTankVolume;
}
One More Requirement
• The manager wants to compute the projected fuel
consumption for a specific trip so that the various
departments can get a proper projection for the cost
of the transportation services. For busses, the fuel
consumption increases by 1% with each passenger.
For a car, the fuel consumption increases by 10%
with each passenger. For truck, one ton of load
increases the fuel consumption by 5%
• Notice that the fuel consumption is measured in
miles per gallon
• Q: Improve the current class diagram and give more
examples
103
Improved Class Diagram
104
Measured in miles
per gallon
AVehicle
- double fuelTankVolume // in gallons
- double averageMilePerGallon
+ double refuelCost(double costPerGallon)
+ double fuelConsumption()
Bus
- int nPassengers
Car
- int nPassengers
Truck
- double loadInTons
More Examples
105
Bus b1 = new Bus(60.0, 10.0, 20);
Car c1 = new Car(15.0, 25.0, 1);
Truck t1 = new Truck(120., 6.0, 0.5);
b1.fuelConsumption()
// should be 8
c1.fuelConsumption()
// should be 22.5
t1.fuelConsumption()
// should be 5.85
fuelConsumption() in AVehicle
106
public abstract class AVehicle {
protected double fuelTankVolume; // in gallons
protected double averageMilePerGallon;
...
protected AVehicle(double fuelTankVolume,
double averageMilePerGallon) {
this.fuelTankVolume = fuelTankVolume;
this.averageMilePerGallon = averageMilePerGallon;
}
public double refuelCost(double costPerGallon) {
return costPerGallon * this.fuelTankVolume;
}
public abstract double fuelConsumption();
}
fuelConsumption() implement
• In this case, all three methods are distinct from each
other, and they must be defined for each specific
concrete class of vehicles.
107
// inside Bus
public double fuelConsumption(){
return this.averageMilePerGallon
* (1 - 1/100 * this.nPassengers);
}
// inside Car
public double fuelConsumption(){
return this.averageMilePerGallon
* (1 - 10/100 * this.nPassengers);
}
// inside Truck
public double fuelConsumption(){
return this.averageMilePerGallon
* (1 - 5/100 * this.loadInTons);
}
Exercise 5.0.9
• Suppose the manager also wants to generate
estimates about how far a vehicle can go,
assuming it is freshly refueled. Design a method
that can compute this estimate for each kind of
vehicle.
108
howFar() in AVehicle
109
public abstract class AVehicle {
protected double fuelTankVolume; // in gallons
protected double averageMilePerGallon;
...
protected Avehicle(double fuelTankVolume,
double averageMilePerGallon) {
this.fuelTankVolume = fuelTankVolume;
this.averageMilePerGallon = averageMilePerGallon;
}
public double refuelCost(double costPerGallon) {
return costPerGallon * this.fuelTankVolume;
}
public abstract double fuelConsumption();
public abstract double howFar();
}
howFar() implement
• Since three subclasses have the same
implementation for howFar(), we could move
this method to the parent class. This means
howFar() now in the AVehicle class will not be
abstract any more
110
public double howFar() {
return this.fuelTankVolume * this.fuelConsumption();
}
Exercises
111
Exercise 5.1.1
• Develop a program that creates a gallery from three different
kinds of records: images (gif), texts (txt), and sounds (mp3).
All have names for source files and sizes (number of bytes).
Images also include information about the height, the width,
and the quality of the image. Texts specify the number of lines
needed for visual representation. Sounds include information
about the playing time of the recording, given in seconds.
• Develop the following methods for this program:
– timeToDownload, which computes how long it takes to download a
file at some network connection speed, typically given in bytes per
second;
– smallerThan, which determines whether the file is smaller than
some given maximum size that can be mailed as an attachment;
– sameName, which determines whether the name of a file is the
same as some given name.
112
Solutions
Exercise 5.1.2
• A software house that is working with a grocery chain receives the
following problem statement:
• Develop a program that keeps track of the items in the grocery
store. For now, assume that the store deals only with ice cream,
coffee, and juice. Each of the items is specified by its brand name,
weight (gram) and price (cents). Each coffee is also labeled as
either regular or decaffeinated. Juice items come in different flavors,
and can be packaged as frozen, fresh, bottled, or canned. Each
package of ice cream specifies its flavor and whether this is a
sorbet, a frozen yogurt, or regular ice cream.
• Design the following methods:
– unitPrice, which computes the unit price (cents per gram) of some grocery
item;
– lowerPrice, which determines whether the unit price of some grocery item
is lower than some given amount;
– cheaperThan, which determines whether a grocery item is cheaper than
some other, given one in terms of the unit cost.
113
Solutions
Exercise 5.1.3
• Recall the class hierarchies concerning taxi
vehicles from exercise 4.1.3:
114
ATaxiVehicle
# int idNum
# int passengers
# int pricePerMile
Cab
Limo
- int minRental
Van
- boolean access
Exercise 5.1.3
Add the following methods to the appropriate classes in the
hierarchy:
• fare, which computes the fare for a vehicle, based on the
number of miles traveled, and using the following
formulas for different vehicles:
– passengers in a cab just pay flat fee per mile
– passengers in a limo must pay at least the minimum rental fee,
otherwise they pay by the mile
– passengers in a van pay $1.00 extra for each passenger
• lowerPrice, which determines whether the fare for a
given number of miles is lower than some amount;
• cheaperThan, which determines whether the fare in one
vehicle is lower than the fare in another vehicle for the
same number of miles.
115
Solutions
Exercise 5.1.4
• Develop a program that assists a bookstore manager in a
discount bookstore. The program should keep a record for
each book. The record must include its title, the author's
name, its price, and its publication year. In addition, the books
There are three kinds of books with different pricing policy.
The hardcover books are sold at 20% off. The sale books are
sold at 50% off. The paperbacks are sold at the list price.
Here are your tasks:
• Develop a class hierarchy for representing books in the
discount bookstore.
• Develop the following methods:
– salePrice, which computes the sale price of each book;
– cheaperThan, which determines whether a book is cheaper than
another book;
– sameAuthor, which determines whether a book was written by
some given author which wrote another book.
116
Solutions
Relax &
…Do Exercises …
117
A gallery Class Diagram
118
Images
- int height
- int width
- String quality
Sounds
- int playingTime // in seconds
AGallery
- String fileName
- int fileSize // number of bytes
+ double timeToDownLoad(double networkSpeed)
+ boolean smallerThan(int maximumSize)
+ boolean sameName(String givenName)
Texts
- int numberOfLines
5.1.1 Solution
119
Back
// inside of AGallery
public double timeToDownLoad(double networkSpeed) {
return this.fileSize/ networkSpeed;
}
public boolean smallerThan(int maximumSize){
return this.fileSize < maximumSize;
}
public boolean sameName(String givenName){
return this.fileName.equals(givenName);
}
5.1.2 Class Diagram
120
AnItem
# String branchName
# double weight
# double price
+ double unitPrice()
+ boolean lowerPrice(double amount)
+ boolean cheaperThan(AnItem that)()
Ice Cream
- String flavor
- String package
Coffee
- String label
Juice
- String flavor
- String package
5.1.2 Solutions
121
public abstract class AnItem {
protected String branchName;
protected double weight;
protected double price;
public AnItem(String branchName, double weight, double price) {
this.branchName = branchName;
this.weight = weight;
this.price = price;
}
public double unitPrice() {
return this.price / this.weight;
}
public boolean lowerPrice(double amount) {
return this.unitPrice() < amount;
}
public boolean cheaperThan(AnItem that) {
return this.unitPrice() < that.unitPrice();
}
}
Ice Cream
122
public class IceCream extends AnItem {
private String flavor;
private String package;
public IceCream(String branchName, double weight,
double price, String flavor,
String package) {
super(branchName, weight, price);
this.flavor = flavor;
this.package = package;
}
}
Coffee
123
public class Coffee extends AnItem {
private String label;
public Coffee(String label, String branchName,
double weight, double price) {
super(branchName, weight, price);
this.label = label;
}
}
Juice
124
back
public class Juice extends AnItem {
private String flavor;
private String package;
public Juice(String branchName, double weight,
double price, String flavor,
String package) {
super(branchName, weight, price);
this.flavor = flavor;
this.package = package;
}
}
Exercise 5.1.3
• Recall the class hierarchies concerning taxi
vehicles from exercise 4.1.3:
125
ATaxiVehicle
# int idNum
# int passengers
# int pricePerMile
Cab
Limo
- int minRental
Van
- boolean access
5.1.3 Class Diagram
126
ATaxiVehicle
# int idNum
# int passengers
# int pricePerMile
+ double fare(double numberOfMiles)
+ boolean lowerPrice(double numberOfMiles, double amount)
+ boolean cheaperThan(double numberOfMiles, ATaxiVehicle that)
Cab
+ double fare(double numberOfMiles)
Limo
- int minRental
+ double fare(double numberOfMiles)
Van
- boolean access
+ double fare(double numberOfMiles)
Solution 5.1.3
127
public abstract class ATaxiVehicle {
protected int idNum;
protected int passengers;
protected int pricePerMile;
public ATaxiVehicle(int idNum, int passengers, int pricePerMile) {
this.idNum = idNum;
this.passengers = passengers;
this.pricePerMile = pricePerMile;
}
public abstract double fare(double numberOfMiles);
public boolean lowerPrice(double numberOfMiles, double amount) {
return this.fare(numberOfMiles) < amount;
}
public boolean cheaperThan(double numberOfMiles, ATaxiVehicle that) {
return this.fare(numberOfMiles) < that.fare(numberOfMiles);
}
}
Cab
128
public abstract class ATaxiVehicle {
protected int idNum;
protected int passengers;
protected int pricePerMile;
public ATaxiVehicle(int idNum, int passengers, int pricePerMile) {
this.idNum = idNum;
this.passengers = passengers;
this.pricePerMile = pricePerMile;
}
public abstract double fare(double numberOfMiles);
public boolean lowerPrice(double numberOfMiles, double amount) {
return this.fare(numberOfMiles) < amount;
}
public boolean cheaperThan(double numberOfMiles, ATaxiVehicle that) {
return this.fare(numberOfMiles) < that.fare(numberOfMiles);
}
}
Limo
129
public class Limo extends ATaxiVehicle {
private int minRental;
public Limo (int minRental, int idNum,
int passengers, int pricePerMile) {
super (idNum,passengers, pricePerMile);
this.minRental = minRental;
}
public double fare( double numberOfMiles) {
if (this.pricePerMile * numberOfMiles< minRental)
return this.minRental;
else
return this.pricePerMile * numberOfMiles;
}
}
Van
130
Back
public class Van extends ATaxiVehicle {
private boolean access;
public Van(boolean access, int idNum,
int passengers, int pricePerMile) {
super (idNum,passengers, pricePerMile);
this.access = access;
}
public double fare(double numberOfMiles) {
return
this.pricePerMile * numberOfMiles + this.passengers;
}
}
5.1.4 Class Diagram
131
ABook
# String title
# String author
# double price
# int publicationYear
+ double salePrice()
+ boolean cheaperThan(ABook that)
+ boolean sameAuthor(ABook that)
Hardcover
+ double salePrice()
Sale
+ double salePrice()
Paperback
+ double salePrice()
5.1.4 Solution
132
public abstract class ABook {
protected String title;
protected String author;
protected double price;
protected int publicationYear;
public ABook(String title, String author,
double price, int publicationYear){
this.title =title;
this.author = author;
this.price = price;
this.publicationYear = publicationYear;
}
public abstract double salePrice();
public boolean cheaperThan(ABook that){
return this.salePrice() < that.salePrice();
}
public boolean sameAuthor(ABook that){
return this.author.equals(that.author);
}
}
Hardcover Book
133
public class Hardcover extends ABook {
public Hardcover(String title, String author,
double price, int publicationYear) {
super (title, author, price, publicationYear);
}
public double salePrice() {
return this.price * 0.8;
}
}
Sale Book
134
public class Sale extends ABook {
public Sale(String title, String author,
double price, int publicationYear) {
super(title, author, price, publicationYear);
}
public double salePrice() {
return this.price * 0.5;
}
}
Paperback Book
135
Back
public class Paperback extends Abook {
public Paperback(String title, String author,
double price, int publicationYear) {
super(title, author, price, publicationYear);
}
public double salePrice() {
return this.price;
}
}

More Related Content

What's hot

tổng hợp bài tập java có đáp án chi tiết
 tổng hợp bài tập java có đáp án chi tiết tổng hợp bài tập java có đáp án chi tiết
tổng hợp bài tập java có đáp án chi tiếtHoàng Trí Phan
 
Chuong 2 phan tich cac thuat toan sap xep va tim kiem
Chuong 2  phan tich cac thuat toan sap xep va tim kiemChuong 2  phan tich cac thuat toan sap xep va tim kiem
Chuong 2 phan tich cac thuat toan sap xep va tim kiemgaconne1985
 
Trigger, Cursor, Function in SQL Server
Trigger, Cursor, Function in SQL ServerTrigger, Cursor, Function in SQL Server
Trigger, Cursor, Function in SQL ServerNguyễn Phúc
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorJussi Pohjolainen
 
Cấu trúc dữ liệu kiểu danh sách liên kết
Cấu trúc dữ liệu kiểu danh sách liên kếtCấu trúc dữ liệu kiểu danh sách liên kết
Cấu trúc dữ liệu kiểu danh sách liên kếthotro
 
C++ Programming.pdf
C++ Programming.pdfC++ Programming.pdf
C++ Programming.pdfMrRSmey
 
Tài liệu tự học Auto lisp
Tài liệu tự học Auto lispTài liệu tự học Auto lisp
Tài liệu tự học Auto lispTrung Thanh Nguyen
 
Đề tài: Thiết kế và chế tạo máy chiết rót bán tự động, HOT, 9đ - Gửi miễn phí...
Đề tài: Thiết kế và chế tạo máy chiết rót bán tự động, HOT, 9đ - Gửi miễn phí...Đề tài: Thiết kế và chế tạo máy chiết rót bán tự động, HOT, 9đ - Gửi miễn phí...
Đề tài: Thiết kế và chế tạo máy chiết rót bán tự động, HOT, 9đ - Gửi miễn phí...Dịch vụ viết bài trọn gói ZALO: 0909232620
 
Co so du lieu t sql
Co so du lieu t sqlCo so du lieu t sql
Co so du lieu t sqlANHMATTROI
 
Bài 6: Các cấu trúc dữ liệu đặc biệt: ngăn xếp, hàng đợi, cây - Giáo trình FPT
Bài 6: Các cấu trúc dữ liệu đặc biệt: ngăn xếp, hàng đợi, cây - Giáo trình FPTBài 6: Các cấu trúc dữ liệu đặc biệt: ngăn xếp, hàng đợi, cây - Giáo trình FPT
Bài 6: Các cấu trúc dữ liệu đặc biệt: ngăn xếp, hàng đợi, cây - Giáo trình FPTMasterCode.vn
 
hệ quản trị cơ sỡ dữ liệu bán vé xem phim
hệ quản trị cơ sỡ dữ liệu bán vé xem phimhệ quản trị cơ sỡ dữ liệu bán vé xem phim
hệ quản trị cơ sỡ dữ liệu bán vé xem phimthuhuynhphonegap
 
Trí tueeuj nhân tạo
Trí tueeuj nhân tạoTrí tueeuj nhân tạo
Trí tueeuj nhân tạoThuần Phong
 
Packages in java
Packages in javaPackages in java
Packages in javajamunaashok
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File HandlingSunil OS
 

What's hot (20)

tổng hợp bài tập java có đáp án chi tiết
 tổng hợp bài tập java có đáp án chi tiết tổng hợp bài tập java có đáp án chi tiết
tổng hợp bài tập java có đáp án chi tiết
 
Chuong 2 phan tich cac thuat toan sap xep va tim kiem
Chuong 2  phan tich cac thuat toan sap xep va tim kiemChuong 2  phan tich cac thuat toan sap xep va tim kiem
Chuong 2 phan tich cac thuat toan sap xep va tim kiem
 
Bai toan du lich
Bai toan du lichBai toan du lich
Bai toan du lich
 
Trigger, Cursor, Function in SQL Server
Trigger, Cursor, Function in SQL ServerTrigger, Cursor, Function in SQL Server
Trigger, Cursor, Function in SQL Server
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
 
Latex main
Latex mainLatex main
Latex main
 
Cấu trúc dữ liệu kiểu danh sách liên kết
Cấu trúc dữ liệu kiểu danh sách liên kếtCấu trúc dữ liệu kiểu danh sách liên kết
Cấu trúc dữ liệu kiểu danh sách liên kết
 
C++ Programming.pdf
C++ Programming.pdfC++ Programming.pdf
C++ Programming.pdf
 
Chuong+1 2-3-4
Chuong+1 2-3-4Chuong+1 2-3-4
Chuong+1 2-3-4
 
Tài liệu tự học Auto lisp
Tài liệu tự học Auto lispTài liệu tự học Auto lisp
Tài liệu tự học Auto lisp
 
Bai giang ROBOT cong nghiep
Bai giang ROBOT cong nghiepBai giang ROBOT cong nghiep
Bai giang ROBOT cong nghiep
 
Đề tài: Thiết kế và chế tạo máy chiết rót bán tự động, HOT, 9đ - Gửi miễn phí...
Đề tài: Thiết kế và chế tạo máy chiết rót bán tự động, HOT, 9đ - Gửi miễn phí...Đề tài: Thiết kế và chế tạo máy chiết rót bán tự động, HOT, 9đ - Gửi miễn phí...
Đề tài: Thiết kế và chế tạo máy chiết rót bán tự động, HOT, 9đ - Gửi miễn phí...
 
Co so du lieu t sql
Co so du lieu t sqlCo so du lieu t sql
Co so du lieu t sql
 
Bài 6: Các cấu trúc dữ liệu đặc biệt: ngăn xếp, hàng đợi, cây - Giáo trình FPT
Bài 6: Các cấu trúc dữ liệu đặc biệt: ngăn xếp, hàng đợi, cây - Giáo trình FPTBài 6: Các cấu trúc dữ liệu đặc biệt: ngăn xếp, hàng đợi, cây - Giáo trình FPT
Bài 6: Các cấu trúc dữ liệu đặc biệt: ngăn xếp, hàng đợi, cây - Giáo trình FPT
 
Bai tap mau pascal
Bai tap mau pascalBai tap mau pascal
Bai tap mau pascal
 
hệ quản trị cơ sỡ dữ liệu bán vé xem phim
hệ quản trị cơ sỡ dữ liệu bán vé xem phimhệ quản trị cơ sỡ dữ liệu bán vé xem phim
hệ quản trị cơ sỡ dữ liệu bán vé xem phim
 
Trí tueeuj nhân tạo
Trí tueeuj nhân tạoTrí tueeuj nhân tạo
Trí tueeuj nhân tạo
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
Phần 4: Thu gom hệ lực
Phần 4: Thu gom hệ lựcPhần 4: Thu gom hệ lực
Phần 4: Thu gom hệ lực
 

Similar to Section4 union of classes and methods

encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingShivam Singhal
 
Topic Use stacks to solve Maze. DO NOT USE RECURSION. And do not us.pdf
Topic Use stacks to solve Maze. DO NOT USE RECURSION. And do not us.pdfTopic Use stacks to solve Maze. DO NOT USE RECURSION. And do not us.pdf
Topic Use stacks to solve Maze. DO NOT USE RECURSION. And do not us.pdfambikacollection1084
 
Requirements Use JavaDo Not Use RecursionDo Not Use Array Lis.pdf
Requirements Use JavaDo Not Use RecursionDo Not Use Array Lis.pdfRequirements Use JavaDo Not Use RecursionDo Not Use Array Lis.pdf
Requirements Use JavaDo Not Use RecursionDo Not Use Array Lis.pdfalphaagenciesindia
 
Pi j3.1 inheritance
Pi j3.1 inheritancePi j3.1 inheritance
Pi j3.1 inheritancemcollison
 
1- Create a class called Point that has two instance variables, defi.pdf
1- Create a class called Point that has two instance variables, defi.pdf1- Create a class called Point that has two instance variables, defi.pdf
1- Create a class called Point that has two instance variables, defi.pdfjeeteshmalani1
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java conceptsChikugehlot
 
Core java concepts
Core java  conceptsCore java  concepts
Core java conceptsRam132
 
Core Java Concepts
Core Java ConceptsCore Java Concepts
Core Java Conceptsmdfkhan625
 
05-OOP-Abstract Classes____________.pptx
05-OOP-Abstract Classes____________.pptx05-OOP-Abstract Classes____________.pptx
05-OOP-Abstract Classes____________.pptxpaautomation11
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1PRN USM
 
C h 04 oop_inheritance
C h 04 oop_inheritanceC h 04 oop_inheritance
C h 04 oop_inheritanceshatha00
 
CGIS_IP_T6_AccessCtrl_ClassScope_Packages_API.pdf
CGIS_IP_T6_AccessCtrl_ClassScope_Packages_API.pdfCGIS_IP_T6_AccessCtrl_ClassScope_Packages_API.pdf
CGIS_IP_T6_AccessCtrl_ClassScope_Packages_API.pdfRosaGomezCano
 
Explain Classes and methods in java (ch04).ppt
Explain Classes and methods in java (ch04).pptExplain Classes and methods in java (ch04).ppt
Explain Classes and methods in java (ch04).pptayaankim007
 
Revisiting SOLID Principles
Revisiting  SOLID Principles Revisiting  SOLID Principles
Revisiting SOLID Principles Anis Ahmad
 

Similar to Section4 union of classes and methods (20)

encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
 
Topic Use stacks to solve Maze. DO NOT USE RECURSION. And do not us.pdf
Topic Use stacks to solve Maze. DO NOT USE RECURSION. And do not us.pdfTopic Use stacks to solve Maze. DO NOT USE RECURSION. And do not us.pdf
Topic Use stacks to solve Maze. DO NOT USE RECURSION. And do not us.pdf
 
Requirements Use JavaDo Not Use RecursionDo Not Use Array Lis.pdf
Requirements Use JavaDo Not Use RecursionDo Not Use Array Lis.pdfRequirements Use JavaDo Not Use RecursionDo Not Use Array Lis.pdf
Requirements Use JavaDo Not Use RecursionDo Not Use Array Lis.pdf
 
Pi j3.1 inheritance
Pi j3.1 inheritancePi j3.1 inheritance
Pi j3.1 inheritance
 
Core java
Core javaCore java
Core java
 
1- Create a class called Point that has two instance variables, defi.pdf
1- Create a class called Point that has two instance variables, defi.pdf1- Create a class called Point that has two instance variables, defi.pdf
1- Create a class called Point that has two instance variables, defi.pdf
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java concepts
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java concepts
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
Core Java Concepts
Core Java ConceptsCore Java Concepts
Core Java Concepts
 
Java for beginners
Java for beginnersJava for beginners
Java for beginners
 
05-OOP-Abstract Classes____________.pptx
05-OOP-Abstract Classes____________.pptx05-OOP-Abstract Classes____________.pptx
05-OOP-Abstract Classes____________.pptx
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1
 
C h 04 oop_inheritance
C h 04 oop_inheritanceC h 04 oop_inheritance
C h 04 oop_inheritance
 
CGIS_IP_T6_AccessCtrl_ClassScope_Packages_API.pdf
CGIS_IP_T6_AccessCtrl_ClassScope_Packages_API.pdfCGIS_IP_T6_AccessCtrl_ClassScope_Packages_API.pdf
CGIS_IP_T6_AccessCtrl_ClassScope_Packages_API.pdf
 
JS OO and Closures
JS OO and ClosuresJS OO and Closures
JS OO and Closures
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java best practices
Java best practicesJava best practices
Java best practices
 
Explain Classes and methods in java (ch04).ppt
Explain Classes and methods in java (ch04).pptExplain Classes and methods in java (ch04).ppt
Explain Classes and methods in java (ch04).ppt
 
Revisiting SOLID Principles
Revisiting  SOLID Principles Revisiting  SOLID Principles
Revisiting SOLID Principles
 

Recently uploaded

Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsSandeep D Chaudhary
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxUmeshTimilsina1
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxannathomasp01
 
Basic Intentional Injuries Health Education
Basic Intentional Injuries Health EducationBasic Intentional Injuries Health Education
Basic Intentional Injuries Health EducationNeilDeclaro1
 

Recently uploaded (20)

Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
Basic Intentional Injuries Health Education
Basic Intentional Injuries Health EducationBasic Intentional Injuries Health Education
Basic Intentional Injuries Health Education
 

Section4 union of classes and methods

  • 1. Unions of Classes and Methods 1
  • 2. The Drawing Program • Develop a drawing program that deals with at least three kinds of shapes: dots, squares, and circles. The shapes are located on a Cartesian grid whose origin is in the northwest. – A dot is located in the grid and is drawn as a small disk of a fixed size (3 pixels). – A square's location is specified via its north-west corner in the grid and its size. – A circle's essential properties are its center point and its radius. 2
  • 3. Class diagram 3 • IShape is the name for a union of variant classes; it is special because it doesn’t contribute any objects to the complete collection. Its sole purpose is to represent the complete collection of object IShape Dot - CartPt location Square - CartPt location - int size Circle - CartPt location - int radius CartPt - int x - int y AShape is one of a Dot, a Square, a Circle Express the relationship between these classes, so that IShape as types of data
  • 4. Class diagram 4 • The AShape class is SUPERCLASS. Dot, Square, and Circle are SUBCLASSES, or REFINES Ashape, or is DERIVED from AShape. • Because all instances of AShape are instances of either Dot, Square, or Circle, we say that AShape is an ABSTRACT CLASS AShape Dot - CartPt location Square - CartPt location - int size Circle - CartPt location - int radius CartPt - int x - int y AShape is one of a Dot, a Square, a Circle Express the relationship between these classes, so that AShape as types of data
  • 5. Java data definitions 5 public class CartPt { private int x; private int y; public CartPt(int x, int y) { this.x = x; this.y = y; } }
  • 6. Java data definitions 6 public interface IShape { } public class Dot implements IShape { private CartPt location; public Dot(CartPt location) { this.location = location; } } public class Square implements IShape { private CartPt location; private int size; public Square(CartPt location, int size) { this.location = location; this.size = size; } } public class Circle implements IShape { private CartPt location; private int radius; public Circle(CartPt location, int radius) { this.location = location; this.radius = radius; } }
  • 7. Test constructors 7 public class ShapeTest extends TestCase { public void testConstructor() { //test for class CartPt CartPt caPt1 = new CartPt(4, 3); CartPt caPt2 = new CartPt(5, 12); CartPt caPt3 = new CartPt(6, 8); // test for class Dot IShape d1 = new Dot(caPt1); IShape d2 = new Dot(caPt2); IShape d3 = new Dot(caPt3); //test for class Circle IShape c1 = new Circle(caPt1, 5); IShape c2 = new Circle(caPt2, 10); IShape c3 = new Circle(caPt3, 12); //test for class Square IShape s1 = new Square(caPt1,5); IShape s2 = new Square(caPt3,10); IShape s3 = new Square(caPt3,12); } }
  • 9. Zoo example • Develop a program that helps a zoo keeper take care of the animals in the zoo. • For now the zoo has lions, snakes, and monkeys. Every animal has a name and weight. The zoo keeper also needs to know how much meat the lion eats per day, the length of each snake, and the favorite food for each monkey • Examples: – The lion Leo weighs 300 pounds and eats 5 pounds of meat every day; – The snake Boa weighs 50 pounds and is 5 feet long; – The monkey George weighs 150 poundds and loves bananas. – The monkey Mina weighs 120 pounds and loves to eat kiwi 9
  • 10. Class diagram 10 IZooAnimal Lion -String name -int weight -int meat Snake -String name -int weight -int lenght Monkey -String name -int weight -String food
  • 11. 11 public interface IZooAnimal{ } public class Lion implements IZooAnimal{ private String name; private int weight; private int meat; public Lion(String name, int weight, int meat) { this.name = name; this.weight = weight; this.meat = meat; } } public class Snake implements IZooAnimal{ private String name; private int weight; private int length; public Snake(String name, int weight, int length) { this.name = name; this.weight = weight; this.length = length; } } public class Monkey implements IZooAnimal{ private String name; private int weight; private String food; public Monkey(String name, int weight, String food) { this.name = name; this.weight = weight; this.food = food; } } Java definitions
  • 12. Test constructor 12 public class AnimalTest extends TestCase { public void testConstructor(){ // test for class Lion IZooAnimal leo = new Lion("Leo", 300, 5); IZooAnimal samba = new Lion("Samba", 200, 3); IZooAnimal Cleopon = new Lion("Cleopon", 250, 5); // test for class Snake IZooAnimal boa = new Snake("Boa", 50,5); IZooAnimal mic = new Snake("Mic", 45,4); IZooAnimal bu = new Snake("Bu", 55,6); // test for class Monkey IZooAnimal george = new Monkey("George", 150, "banana"); IZooAnimal mina = new Monkey("Mina", 120, "Kiwi"); IZooAnimal slan = new Monkey("Slan", 100, "Kiwi"); } }
  • 13. Common Data • Notice that, three subclasses have one thing in common, namely, a location. That is, each dot, square, or circle has a location. • Subclasses have the commonalities and the differences. – tend to attribute the commonalities to the superclass, and the differences to the subclasses. 13 Dot Square - int size Circle - int radius AShape # CartPt location CartPt - int x - int y Subclasses inherits the location field from Ashape superclass
  • 14. Java data definitions 14 public abstract class AShape { protected CartPt location; } public class Dot extends AShape { } public class Square extends AShape { private int size; } public class Circle extends AShape { private int radius; }
  • 15. Contructor of AShape 15 Two constructor format of Square public abstract class AShape { protected CartPt location; protected Ashape(CartPt location) { this.location = location; } } public abstract class AShape { protected CartPt location; } public class Square extends AShape { private int size; public Square(CartPt location, int size) { this.location = location; this.size = size; } } public class Square extends AShape { private int size; public Square(CartPt location, int size) { super(location); this.size = size; } } access protected location field inherits form AShape call constructor of Ashape superclass
  • 16. Final Java data definitions (format 1) 16 public abstract class AShape { protected CartPt location; } public class Dot extends AShape { public Dot(CartPt location) { this.location = location; } } public class Square extends AShape { private int size; public Square(CartPt location, int size) { this.location = location; this.size = size; } } public class Circle extends AShape { private int radius; public Circle(CartPt location, int radius) { this.location = location; this.radius = radius; } } Subclasses can access protected location common field inherits form AShape
  • 17. Final Java data definitions (format 2) 17 public abstract class AShape { protected CartPt location; protected Ashape(CartPt location) { this.location = location; } } public class Dot extends AShape { public Dot(CartPt location) { super(location); } } public class Square extends AShape { private int size; public Square(CartPt location, int size) { super(location); this.size = size; } } public class Circle extends AShape { private int radius; public Circle(CartPt location, int radius) { super(location); this.radius = radius; } } Subclasses call constructor of Ashape superclass
  • 18. Keyword • abstract in front of a class indicates – The class is abstract. – there are no instances of this class. • can not use new operator to create an object of this class. • extends – makes the Dot class a refinement or an extension of AShape therefore INHERITS all of AShape's fields. 18
  • 19. protected attribute and method • protected: the class itself and its subclass can access this attribute / method. • Q: Review public and private modifiers for attribute and method. – public: Classes in all packages can see this attribute and method. – private: the class itself can access this attribute / method. – None modifier: Classes in the same package can access attribute and method. 19
  • 20. Modifiers for class • None modifier: Classes in the same package can see this class. • public: Classes in all packages can see this class. 20
  • 21. Test constructors 21 public class ShapeTest extends TestCase { public void testConstructor() { //test for class CartPt CartPt caPt1 = new CartPt(4, 3); CartPt caPt2 = new CartPt(5, 12); CartPt caPt3 = new CartPt(6, 8); // test for class Dot AShape d1 = new Dot(caPt1); AShape d2 = new Dot(caPt2); AShape d3 = new Dot(caPt3); //test for class Circle AShape c1 = new Circle(caPt1, 5); AShape c2 = new Circle(caPt2, 10); AShape c3 = new Circle(caPt3, 12); //test for class Square AShape s1 = new Square(caPt1,5); AShape s2 = new Square(caPt3,10); AShape s3 = new Square(caPt3,12); } }
  • 22. Types vs Classes • A type describes for what kind of objects a variable or a parameter • In Java, a type is either the name of an interface, a class, or a primitive type (int, double, boolean or String). • When we write: AShape s; – s has type AShape – which means that it is a placeholder for some unknown shape. • Similarly, when we introduce an example such as AShape s = new Square(...) – s has type AShape, even though we know that it stands for an instance of Square. 22
  • 24. Zoo example • Develop a program that helps a zoo keeper take care of the animals in the zoo. • For now the zoo has lions, snakes, and monkeys. Every animal has a name and weight. The zoo keeper also needs to know how much meat the lion eats per day, the length of each snake, and the favorite food for each monkey • Examples: – The lion Leo weighs 300 pounds and eats 5 pounds of meat every day; – The snake Boa weighs 50 pounds and is 5 feet long; – The monkey George weighs 150 poundds and loves bananas. – The monkey Mina weighs 120 pounds and loves to eat kiwi 24
  • 25. Class diagram 25 Animal # String name # int weight Lion - int meat Snake - int lenght Monkey - String food
  • 26. 26 public abstract class Animal { protected String name; protected int weight; } public class Lion extends Animal { private int meat; public Lion(String name, int weight, int meat) { this.name = name; this.weight = weight; this.meat = meat; } } public class Snake extends Animal { private int length; public Snake(String name, int weight, int length) { this.name = name; this.weight = weight; this.length = length; } } public class Monkey extends Animal { private String food; public Monkey(String name, int weight, String food) { this.name = name; this.weight = weight; this.food = food; } } Java definitions
  • 27. 27 public abstract class Animal { protected String name; protected int weight; protected Animal(String name, int weight) { this.name = name; this.weight = weight; } } public class Lion extends Animal { private int meat; public Lion(String name, int weight, int meat) { super(name, weight); this.meat = meat; } } public class Snake extends Animal { private int length; public Snake(String name, int weight, int length) { super(name, weight); this.length = length; } } public class Monkey extends Animal { private String food; public Monkey(String name, int weight, String food) { super(name, weight); this.food = food; } } Java definitions Subclasses call a contructor of super class
  • 28. Test constructor 28 public class AnimalTest extends TestCase { public void testConstructor(){ // test for class Lion Animal leo = new Lion("Leo", 300, 5); Animal samba = new Lion("Samba", 200, 3); Animal cleopon = new Lion("Cleopon", 250, 5); // test for class Snake Animal boa = new Snake("Boa", 50,5); Animal mic = new Snake("Mic", 45,4); Animal bu = new Snake("Bu", 55,6); // test for class Monkey Animal george = new Monkey("George", 150, "banana"); Animal mina = new Monkey("Mina", 120, "Kiwi"); Animal slan = new Monkey("Slan", 100, "Kiwi"); } }
  • 29. “this” and “super” keyword • this: references to instance itself. • super: references to superclass. 29
  • 30. Exercises Part I: Exercise 4.1.1 to 4.1.4 (HTDCH) Do in class 4.1.1 30
  • 31. Exercise 4.1.1 Design a data representation for this problem: . . . Develop a “bank account” program. The program keeps track of the balances in a person’s bank accounts. Each account has an id number and a customer’s name. There are three kinds of accounts: a checking account, a savings account, and a certificate of deposit (CD). Checking account information also includes the minimum balance. Savings account includes the interest rate. A CD specifies the interest rate and the maturity date. Naturally, all three types come with a current balance. . . . • Represent the following examples using your classes: – 1. Earl Gray, id# 1729, has $1,250 in a checking account with minimum balance of $500; – 2. Ima Flatt, id# 4104, has $10,123 in a certificate of deposit whose interest rate is 4% and whose maturity date is June 1, 2005; – 3. Annie Proulx, id# 2992, has $800 in a savings account; the account yields interest at the rate of 3.5%. 31
  • 32. Exercise 4.1.2 • Develop a program that creates a gallery from three different kinds of records: images (gif), texts (txt), and sounds (mp3). All have names for source files and sizes (number of bytes). Images also include information about the height, the width, and the quality of the image. Texts specify the number of lines needed for visual representation. Sounds include information about the playing time of the recording, given in seconds. • Examples: – an image, stored in flower.gif; size: 57,234 bytes; width: 100 pixels; height: 50 pixels; quality: medium; – a text, stored in welcome.txt; size: 5,312 bytes; 830 lines; – a music piece, stored in theme.mp3; size: 40960 bytes, playing time 3 minutes and 20 seconds. 32
  • 33. Extended exercises • Exercise 7.2.2 (HTDP). The administrators of metropolitan transportation agencies manage fleets of vehicles. Develop data definitions for a collection of such vehicles. The collection should include at least buses, limos, cars, and subways. Add at least two attributes per class of vehicle. 33
  • 35. Design methods for unions of classes 35
  • 36. Recall the Drawing Program 36 Dot Square - int size Circle - int radius AShape # CartPt location CartPt - int x - int y 11
  • 37. Requirements 1. Compute the area of a shape 2. Compute the distance of a shape to the origin 3. Determine whether some point is inside the shape 4. Compute the bounding box of a shape • All of these methods clearly work with shapes in general but may have to compute different results depending on the concrete shape on which they are invoked – For example, a Dot has no true area; a Square's area is computed differently from a Circle's area • In an object-oriented language, we can indicate that all AShape's have such method with ABSTRACT methods 37
  • 38. Add method for union 38
  • 39. Add method for Shape 39 Dot Square - int size Circle - int radius AShape # CartPt location CartPt - int x - int y 11 ??? mmm() ??? mmm() ??? mmm() ??? mmm() ??? kkk()
  • 40. 1. Computing Area of A Shape 40
  • 41. Augmenting Ashape area() purpose and signature public abstract class AShape { protected CartPt location; protected AShape(CartPt location) { this.location = location; } // compute area of AShape public abstract double area(); } 41 Q: Create a method template for each of the subclasses of AShape
  • 42. Abstract Methods • An abstract method isn't a method; it is just a method signature preceded with the keyword abstract • An abstract method must be defined in an abstract class, and announces that the concrete subclasses have CONCRETE METHODS with the same signature and a proper method body 42
  • 43. Template for area() of Dot 43 Tips: a class extends other class, it inherits all fields of this class such as Circle, Square,Dot extends AShape so that it inherit field "location" of AShape class. public class Dot extends AShape { public Dot(CartPt location) { super(location); } public double area() { ...this.location... } }
  • 44. Template for area() of Square 44 public class Square extends AShape { private int size; public Square(CartPt location, int size) { super(location); this.size = size; } public double area() { ...this.location... ...this.size... } }
  • 45. Template for area() of Circle 45 Q: Do the Example step public class Circle extends AShape { private int radius; public Circle(CartPt location, int radius) { super(location); this.radius = radius; } public double area() { ...this.location... ...this.radius... } }
  • 46. Add method to class diagram 46 Dot + double area() Square - int size + double area() Circle - int radius + double area() AShape # CartPt location + double area() CartPt - int x - int y
  • 47. Examples • new Dot(new CartPt(4, 3)).area() // should be 0.0 • new Square(new CartPt(4, 3), 30).area() // should be 900.0 • new Circle(new CartPt(5, 5), 20).area() // should be 1256.6... 47 Q: Implement the body of all area() methods
  • 48. Implement area() method 48 // inside of Dot public double area() { return 0.0; } // inside of Circle public double area() { return Math.PI * this.radius * this.radius; } // inside of Square public double area() { return this.size * this.size; }
  • 49. Unit Testing 49 public class AShapeTest extends TestCase { public void testArea() { assertEquals(new Dot(new CartPt(4, 3)) .area(), 0.0, 0.01); assertEquals(new Square(new CartPt(4, 3), 30) .area(), 900, 0.01); assertEquals(new Circle(new CartPt(5, 5), 20) .area(), 1256.64, 0.01); } }
  • 50. Polymorphism • With the same call area(), but each concrete subclass deal with it in difference way. 50 Polymorphism
  • 51. 2. Computing the distance of a shape to the origin 51
  • 52. Distance of a shape to the origin What is the distance between a shape and the origin? 52 X Y 0
  • 53. distanceToO() purpose and signature 53 public abstract class AShape { protected CartPt location; protected AShape(CartPt location) { this.location = location; } public abstract double area(); // to compute the distance of this shape // to the origin public abstract double distanceToO(); }
  • 54. Same implement distanceToO() 54 // inside of Dot public double distanceToO() { return this.location.distanceToO(); } // inside of Circle public double distanceToO() { return this.location.distanceToO(); } // inside of Square public double distanceToO() { return this.location.distanceToO(); }
  • 55. Extracting Common Methods to Subclasses • Q: Is there any difference in the implementations of distanceToO() in all the subclasses • A: No, there is no difference at all • To remove similarities, we could pull distanceToO() up to the superclass AShape 55
  • 56. Pull distanceToO() up to AShape 56 public abstract class AShape { protected CartPt location; public abstract double area(); public double distanceToO() { return this.location.distanceToO(); } } public class CartPt { private int x; private int y; public double distanceToO() { return Math.sqrt(this.x * this.x + this.y * this.y); } }
  • 57. Unit Test 57 public void testDistanceToO() { assertEquals(new Dot(new CartPt(4, 3)) .distanceToO(), 5.0, 0.001); assertEquals(new Square(new CartPt(4, 3), 30) .distanceToO(), 5.0, 0.001); assertEquals(new Circle(new CartPt(12, 5), 20) .distanceToO(), 13.0, 0.001); }
  • 58. Class diagram 58 Dot + double area() Square - int size + double area() Circle - int radius + double area() AShape # CartPt location + double area() + double distanceToO() CartPt - int x - int y + double distanceToO()
  • 59. 3. Determining whether some point is inside the shape 59
  • 60. Is point inside the shape A given point is inside a DOT when its distance to this DOT is 0. a given point is inside a CIRCLE if its distance to the center of the CIRCLE is less than or equal the radius. A given point is inside a SQUARE when it is between two pairs of lines. 60
  • 61. contains() purpose and signature 61 Q: Create a method template for each of the subclasses of AShape and do the Example step public abstract class AShape { protected CartPt location; protected AShape(CartPt location) { this.location = location; } public double distanceToO() { return this.location.distanceToO(); } public abstract double area(); // is the given point is within the bounds of this shape public abstract boolean contains(CartPt point); }
  • 62. Examples • new Dot(new CartPt(100, 200)) .contains(new CartPt(100, 200)) // should be true • new Dot(new CartPt(100, 200)) .contains(new CartPt(80, 220)) // should be false • new Square(new CartPt(100, 200), 40) .contains(new CartPt(120, 220)) // should be true • new Square(new CartPt(100, 200), 40) .contains(new CartPt(80, 220)) // should be false • new Circle(new CartPt(0, 0),20) .contains(new CartPt(4, 3)) // should be true • new Circle(new CartPt(0, 0), 10) .contains(new CartPt(12, 5)) // should be false 62
  • 63. Domain Knowledge • How to determine whether some point is inside the shape is a kind of knowledge called DOMAIN KNOWLEDGE • To comprehend the domain knowledge, we sometimes look up in a book and in other situations we gather from experts 63
  • 64. Implement contains() 64 // inside of Dot public boolean contains(CartPt point) { return this.location.distanceTo(point) == 0.0; } // inside of Circle public boolean contains(CartPt point) { return this.location.distanceTo(point) <= this.radius; }
  • 65. distanceTo() in CartPt 65 public class CartPt { private int x; private int y; public CartPt(int x, int y) { this.x = x; this.y = y; } public double distanceToO() { return Math.sqrt(this.x * this.x + this.y * this.y); } // compute distance of this point to another point public double distanceTo(CartPt that) { double diffX = this.x - that.x; double diffY = this.y - that.y; return Math.sqrt(diffX * diffX + diffY * diffY); } }
  • 66. Implement contains() in Square 66 size size x + size y + size location O x y
  • 67. 67 // inside of Square public boolean contains(CartPt point) { int thisX = this.location.getX(); int thisY = this.location.getY(); return this.between(point.getX(), thisX, thisX + this.size) && this.between(point.getY(), thisY, thisY + this.size); } //----------------------------------------------------------- private boolean between(int value, int low, int high) { return (low <= value) && (value <= high); } // inside of CartPt public class CartPt { private int x; private int y; public int getX() { return this.x; } public int getY() { return this.y; } }
  • 68. Unit test 68 public void testContain(){ assertTrue(new Dot(new CartPt(100, 200)) .contains(new CartPt(100, 200))); assertFalse(new Dot(new CartPt(100, 200)) .contains(new CartPt(80, 220))); assertTrue(new Square(new CartPt(100, 200),40) .contains(new CartPt(120, 220))); assertFalse(new Square(new CartPt(100, 200),40) .contains(new CartPt(80, 220))); assertTrue(new Circle(new CartPt(0, 0),20) .contains(new CartPt(4, 3))); assertFalse(new Circle(new CartPt(0, 0),10) .contains(new CartPt(12, 5))); }
  • 69. Class diagram 69 Dot + double area() + boolean contains(CartPt point) Square - int size + double area() + boolean contains(CartPt point) Circle - int radius + double area() + boolean contains(CartPt point) AShape # CartPt location + double area() + double distanceToO() + boolean contains(CartPt point) CartPt - int x - int y + double distanceToO() + double distanceTo(CartPt that)
  • 70. 4. Computing the bounding box of a shape 70
  • 71. What is a Bounding Box? • A bounding box is the smallest square that completely surrounds the given shape – The bounding box for a Square is the given square itself. – For a Circle, the bounding box is also a square, • its width and height are 2 * radius and • its northwest corner is one radius removed from the center of the circle in both directions. – The bounding box for a Dot is a square with no extent. Mathematicians call this idea a special case 71 Q: Add the boundingBox() method to AShape
  • 72. Class diagram 72 Dot + double area() + boolean contains(CartPt point) + Square boundingBox() Square - int size + double area() + boolean contains(CartPt point) + Square boundingBox() Circle - int radius + double area() + boolean contains(CartPt point) + Square boundingBox() AShape # CartPt location + double area() + double distanceToO() + boolean contains(CartPt point) + Square boundingBox() CartPt - int x - int y + double distanceToO() + double distanceTo(CartPt that)
  • 73. boundingBox purpose and signature 73 public abstract class AShape { protected CartPt location; protected AShape(CartPt location) { this.location = location; } public double distanceToO() { return this.location.distanceToO(); } public abstract double area(); public abstract boolean contains(CartPt point); // compute the bounding box for this shape public abstract Square boundingBox(); }
  • 74. Examples 74 new Dot(new CartPt(100, 100)).boundingBox() // should be new Square(new CartPt(100, 100), 0) new Square(new CartPt(100, 100), 40).boundingBox() // should be new Square(new CartPt(100, 100), 40) new Circle(new CartPt(0, 0), 20).boundingBox() // should be new Square(new CartPt(-20, -20), 40)
  • 75. Implement boundingBox() method 75 // inside of Square public Square boundingBox() { return new Square(this.location, this.size); } // inside of Dot public Square boundingBox() { return new Square(this.location, 0); }
  • 76. boundingBox method in Circle 76 public Square boundingBox() { return new Square(this.location.translate( -this.radius, -this.radius), this.radius * 2); } // inside of CartPt // translate this point to deltaX, deltaY distance public CartPt translate(int deltaX, int deltaY) { return new CartPt(this.x + deltaX, this.y + deltaY); }
  • 77. Unit test 77 public void testBoudingBox(){ assertTrue(new Dot(new CartPt(4, 3)).boundingBox() .equals(new Square(new CartPt(4, 3), 0))); assertTrue(new Circle(new CartPt(5, 5), 5).boundingBox() .equals(new Square(new CartPt(0, 0), 10))); assertTrue(new Square(new CartPt(4, 3), 30).boundingBox() .equals(new Square(new CartPt(4, 3), 30))); }
  • 78. equals method 78 // inside of Square class public boolean equals(Object obj) { if (null==obj || !(obj instanceof Square)) return false; else { Square that = (Square) obj; return (this.location.equals(that.location) && this.size == that.size); } } // inside of CartPt class public boolean equals(Object obj) { if (null==obj || !(obj instanceof CartPt)) return false; else { CartPt that = (CartPt) obj; return (this.x == that.x) && (this.y == that.y); } }
  • 79. Overriding method • The supper class and suclass have the same method (same name and same parameters, same return data type). • Method in subclass disables method in supper class. 79
  • 80. “Overiding” or “Overloading” • All classes in Java extends Object class • Q: distinguish “overloading” and “overriding” ? • A: – Method equals(Object) in class Square is called overriding method equals(Object) in class Object. – Method area() and area(Cirlce) in class Cirlce have the same name but different parameter is called overloading. • When we invoke overloading methods, the method with appropriate argument will do 80
  • 81. A Summary of Important Points 1. How helpful the template-directed design is 2. The refinement arrows let us know where to place abstract methods and concrete methods 3. The containment arrow reminds us that we can place auxiliary methods in those classes so that each object performs the appropriate method calculations in the end. 81
  • 83. Exercise 5.0.4 • Draw a class diagram for the classes in the shape hierarchy 83 CartPt - int x - int y + int getX() + int getY() + double distanceToO() + double distanceTo(CartPt that) + void translate(int dx, int dy) AShape # CartPt location # AShape(CartPt location) + double distanceToO() + double area() + boolean contains(CartPt point) + Square boundingBox() 1 Dot Square - int size - boolean between(int value, int low, int high) Circle - int radius
  • 84. Exercise 5.0.5 • Design an extension for the class hierarchy of shapes that deals with Rectangles. The extension should cope with all the abstract methods in AShape 84
  • 85. Solution 5.0.5 85 Q: Both Square and Rectangle do need the method between(). Remove similarities in these two classes A: Since between() could exist independently, that it does not need to belong to any of the existing classes, it could be put in a helping class CartPt - int x - int y + int getX() + int getY() + double distanceToO() + double distanceTo(CartPt that) + void translate(int dx, int dy) AShape # CartPt location # AShape(CartPt location) + double distanceToO() + double area() + boolean contains(CartPt point) + Rectangle boundingBox() 11 Dot Square - int size Circle - int radius Rectangle - int width - int height
  • 86. Solution 5.0.5: Improved Design 86 CartPt - int x - int y + int getX() + int getY() + double distanceToO() + double distanceTo(CartPt that) + void translate(int dx, int dy) AShape # CartPt location # AShape(CartPt location) + double distanceToO() + double area() + boolean contains(CartPt point) + Rectangle boundingBox() 11 Dot Square - int size Circle - int radius Rectangle - int width - int height ShapeUtils <<static>> + boolean between(int value, int low, int high) uses uses
  • 87. Solution 5.0.5: ShapeUtils 87 public class ShapeUtils { public static boolean between(int value, int low, int high) { return (low <= value) && (value <= high); } }
  • 88. static modifier for attribute and method • static: classes can access this attribute/ method without create an instance of class which contains it. 88
  • 89. Solution 5.0.5: Rectangle 89 public class Rectangle extends AShape { private int width; private int height; public Rectangle(CartPt location, int width, int height) { … } public double area() { return this.width * this.height; } public boolean contains(CartPt point) { int thisX = this.location.getX(); int thisY = this.location.getY(); return ShapeUtils.between(point.getX(), thisX, thisX + this.width) && ShapeUtils.between(point.getY(), thisY, thisY + this.height); } public Rectangle boundingBox() { return new Rectangle(this.location, width, height); } }
  • 90. Exercise 5.0.6 • Design an extension for the class hierarchy of shapes so that a program can request the length of the perimeter for each shape in the hierarchy 90
  • 91. Solution 5.0.6 91 CartPt - int x - int y + int getX() + int getY() + double distanceToO() + double distanceTo(CartPt that) + void translate(int dx, int dy) AShape # CartPt location # AShape(CartPt location) + double distanceToO() + double area() + boolean contains(CartPt point) + Rectangle boundingBox() + double perimeter() 11 Dot Square - int size Circle - int radius Rectangle - int width - int height ShapeUtils <<static>> + boolean between(int left, int mid, int right) uses uses
  • 92. Solution 5.0.6 (cont.) 92 // in Dot public double perimeter() { return 1.0; } // in Square public double perimeter() { return this.size * 4; } // in Rectangle public double perimeter() { return (this.width + this.height) * 2; } // in Circle public double perimeter() { return this.radius * 2 * Math.PI; }
  • 93. Extended exercise • Compute the bounding box the class hierarchy of shapes that deals with Rectangles. The extension should cope with all the abstract methods in AShape • This is a very interesting exercise ! 93
  • 95. The Fuel Consumption Problem 95
  • 96. Problem Statement • A school district needs to manage the fuel consumption for its fleet of vehicles, which includes school busses, cars, and trucks. Each vehicle has a fuel tank of some size (in gallons). The district also knows the average mile-per-gallon consumption of fuel per vehicle. The fuel consumption for cars and busses depends on the number of passengers the vehicle carries; the fuel consumption of a truck increases with its load (in tons) 96
  • 97. Class Diagram 97 AVehicle - double fuelTankVolume // in gallons - double averageMilePerGallon Bus - int nPassengers Car - int nPassengers Truck - double loadInTons
  • 98. Examples 98 Car c1 = new Car(15.0, 25.0, 1); Truck t1 = new Truck(120., 6.0, 0.5); Bus b1 = new Bus(60.0, 10.0, 20);
  • 99. Requirement • The manager needs to know how much it costs to refuel a vehicle with empty fuel tank at the current fuel prices so that the district can create estimates for the gas budget • Q: Improve the current class diagram and give more examples 99
  • 100. Improved Class Diagram 100 AVehicle - double fuelTankVolume // in gallons - double averageMilePerGallon + double refuelCost(double costPerGallon) Bus - int nPassengers Car - int nPassengers Truck - double loadInTons
  • 101. More Examples 101 Bus b1 = new Bus(60.0, 10.0, 20); Car c1 = new Car(15.0, 25.0, 1); Truck t1 = new Truck(120., 6.0, 0.5); b1.refuelCost(2.00) // should be 120.0 c1.refuelCost(2.00) // should be 30.0 t1.refuelCost(2.00) // should be 240.0
  • 102. Implementation of refuelCost() • Since three subclasses have the same implementation for refuelCost(), we could move this method to the parent class. This means refuelCost() now in the AVehicle class will not be abstract any more 102 public double refuelCost(double costPerGallon) { return costPerGallon * this.fuelTankVolume; }
  • 103. One More Requirement • The manager wants to compute the projected fuel consumption for a specific trip so that the various departments can get a proper projection for the cost of the transportation services. For busses, the fuel consumption increases by 1% with each passenger. For a car, the fuel consumption increases by 10% with each passenger. For truck, one ton of load increases the fuel consumption by 5% • Notice that the fuel consumption is measured in miles per gallon • Q: Improve the current class diagram and give more examples 103
  • 104. Improved Class Diagram 104 Measured in miles per gallon AVehicle - double fuelTankVolume // in gallons - double averageMilePerGallon + double refuelCost(double costPerGallon) + double fuelConsumption() Bus - int nPassengers Car - int nPassengers Truck - double loadInTons
  • 105. More Examples 105 Bus b1 = new Bus(60.0, 10.0, 20); Car c1 = new Car(15.0, 25.0, 1); Truck t1 = new Truck(120., 6.0, 0.5); b1.fuelConsumption() // should be 8 c1.fuelConsumption() // should be 22.5 t1.fuelConsumption() // should be 5.85
  • 106. fuelConsumption() in AVehicle 106 public abstract class AVehicle { protected double fuelTankVolume; // in gallons protected double averageMilePerGallon; ... protected AVehicle(double fuelTankVolume, double averageMilePerGallon) { this.fuelTankVolume = fuelTankVolume; this.averageMilePerGallon = averageMilePerGallon; } public double refuelCost(double costPerGallon) { return costPerGallon * this.fuelTankVolume; } public abstract double fuelConsumption(); }
  • 107. fuelConsumption() implement • In this case, all three methods are distinct from each other, and they must be defined for each specific concrete class of vehicles. 107 // inside Bus public double fuelConsumption(){ return this.averageMilePerGallon * (1 - 1/100 * this.nPassengers); } // inside Car public double fuelConsumption(){ return this.averageMilePerGallon * (1 - 10/100 * this.nPassengers); } // inside Truck public double fuelConsumption(){ return this.averageMilePerGallon * (1 - 5/100 * this.loadInTons); }
  • 108. Exercise 5.0.9 • Suppose the manager also wants to generate estimates about how far a vehicle can go, assuming it is freshly refueled. Design a method that can compute this estimate for each kind of vehicle. 108
  • 109. howFar() in AVehicle 109 public abstract class AVehicle { protected double fuelTankVolume; // in gallons protected double averageMilePerGallon; ... protected Avehicle(double fuelTankVolume, double averageMilePerGallon) { this.fuelTankVolume = fuelTankVolume; this.averageMilePerGallon = averageMilePerGallon; } public double refuelCost(double costPerGallon) { return costPerGallon * this.fuelTankVolume; } public abstract double fuelConsumption(); public abstract double howFar(); }
  • 110. howFar() implement • Since three subclasses have the same implementation for howFar(), we could move this method to the parent class. This means howFar() now in the AVehicle class will not be abstract any more 110 public double howFar() { return this.fuelTankVolume * this.fuelConsumption(); }
  • 112. Exercise 5.1.1 • Develop a program that creates a gallery from three different kinds of records: images (gif), texts (txt), and sounds (mp3). All have names for source files and sizes (number of bytes). Images also include information about the height, the width, and the quality of the image. Texts specify the number of lines needed for visual representation. Sounds include information about the playing time of the recording, given in seconds. • Develop the following methods for this program: – timeToDownload, which computes how long it takes to download a file at some network connection speed, typically given in bytes per second; – smallerThan, which determines whether the file is smaller than some given maximum size that can be mailed as an attachment; – sameName, which determines whether the name of a file is the same as some given name. 112 Solutions
  • 113. Exercise 5.1.2 • A software house that is working with a grocery chain receives the following problem statement: • Develop a program that keeps track of the items in the grocery store. For now, assume that the store deals only with ice cream, coffee, and juice. Each of the items is specified by its brand name, weight (gram) and price (cents). Each coffee is also labeled as either regular or decaffeinated. Juice items come in different flavors, and can be packaged as frozen, fresh, bottled, or canned. Each package of ice cream specifies its flavor and whether this is a sorbet, a frozen yogurt, or regular ice cream. • Design the following methods: – unitPrice, which computes the unit price (cents per gram) of some grocery item; – lowerPrice, which determines whether the unit price of some grocery item is lower than some given amount; – cheaperThan, which determines whether a grocery item is cheaper than some other, given one in terms of the unit cost. 113 Solutions
  • 114. Exercise 5.1.3 • Recall the class hierarchies concerning taxi vehicles from exercise 4.1.3: 114 ATaxiVehicle # int idNum # int passengers # int pricePerMile Cab Limo - int minRental Van - boolean access
  • 115. Exercise 5.1.3 Add the following methods to the appropriate classes in the hierarchy: • fare, which computes the fare for a vehicle, based on the number of miles traveled, and using the following formulas for different vehicles: – passengers in a cab just pay flat fee per mile – passengers in a limo must pay at least the minimum rental fee, otherwise they pay by the mile – passengers in a van pay $1.00 extra for each passenger • lowerPrice, which determines whether the fare for a given number of miles is lower than some amount; • cheaperThan, which determines whether the fare in one vehicle is lower than the fare in another vehicle for the same number of miles. 115 Solutions
  • 116. Exercise 5.1.4 • Develop a program that assists a bookstore manager in a discount bookstore. The program should keep a record for each book. The record must include its title, the author's name, its price, and its publication year. In addition, the books There are three kinds of books with different pricing policy. The hardcover books are sold at 20% off. The sale books are sold at 50% off. The paperbacks are sold at the list price. Here are your tasks: • Develop a class hierarchy for representing books in the discount bookstore. • Develop the following methods: – salePrice, which computes the sale price of each book; – cheaperThan, which determines whether a book is cheaper than another book; – sameAuthor, which determines whether a book was written by some given author which wrote another book. 116 Solutions
  • 118. A gallery Class Diagram 118 Images - int height - int width - String quality Sounds - int playingTime // in seconds AGallery - String fileName - int fileSize // number of bytes + double timeToDownLoad(double networkSpeed) + boolean smallerThan(int maximumSize) + boolean sameName(String givenName) Texts - int numberOfLines
  • 119. 5.1.1 Solution 119 Back // inside of AGallery public double timeToDownLoad(double networkSpeed) { return this.fileSize/ networkSpeed; } public boolean smallerThan(int maximumSize){ return this.fileSize < maximumSize; } public boolean sameName(String givenName){ return this.fileName.equals(givenName); }
  • 120. 5.1.2 Class Diagram 120 AnItem # String branchName # double weight # double price + double unitPrice() + boolean lowerPrice(double amount) + boolean cheaperThan(AnItem that)() Ice Cream - String flavor - String package Coffee - String label Juice - String flavor - String package
  • 121. 5.1.2 Solutions 121 public abstract class AnItem { protected String branchName; protected double weight; protected double price; public AnItem(String branchName, double weight, double price) { this.branchName = branchName; this.weight = weight; this.price = price; } public double unitPrice() { return this.price / this.weight; } public boolean lowerPrice(double amount) { return this.unitPrice() < amount; } public boolean cheaperThan(AnItem that) { return this.unitPrice() < that.unitPrice(); } }
  • 122. Ice Cream 122 public class IceCream extends AnItem { private String flavor; private String package; public IceCream(String branchName, double weight, double price, String flavor, String package) { super(branchName, weight, price); this.flavor = flavor; this.package = package; } }
  • 123. Coffee 123 public class Coffee extends AnItem { private String label; public Coffee(String label, String branchName, double weight, double price) { super(branchName, weight, price); this.label = label; } }
  • 124. Juice 124 back public class Juice extends AnItem { private String flavor; private String package; public Juice(String branchName, double weight, double price, String flavor, String package) { super(branchName, weight, price); this.flavor = flavor; this.package = package; } }
  • 125. Exercise 5.1.3 • Recall the class hierarchies concerning taxi vehicles from exercise 4.1.3: 125 ATaxiVehicle # int idNum # int passengers # int pricePerMile Cab Limo - int minRental Van - boolean access
  • 126. 5.1.3 Class Diagram 126 ATaxiVehicle # int idNum # int passengers # int pricePerMile + double fare(double numberOfMiles) + boolean lowerPrice(double numberOfMiles, double amount) + boolean cheaperThan(double numberOfMiles, ATaxiVehicle that) Cab + double fare(double numberOfMiles) Limo - int minRental + double fare(double numberOfMiles) Van - boolean access + double fare(double numberOfMiles)
  • 127. Solution 5.1.3 127 public abstract class ATaxiVehicle { protected int idNum; protected int passengers; protected int pricePerMile; public ATaxiVehicle(int idNum, int passengers, int pricePerMile) { this.idNum = idNum; this.passengers = passengers; this.pricePerMile = pricePerMile; } public abstract double fare(double numberOfMiles); public boolean lowerPrice(double numberOfMiles, double amount) { return this.fare(numberOfMiles) < amount; } public boolean cheaperThan(double numberOfMiles, ATaxiVehicle that) { return this.fare(numberOfMiles) < that.fare(numberOfMiles); } }
  • 128. Cab 128 public abstract class ATaxiVehicle { protected int idNum; protected int passengers; protected int pricePerMile; public ATaxiVehicle(int idNum, int passengers, int pricePerMile) { this.idNum = idNum; this.passengers = passengers; this.pricePerMile = pricePerMile; } public abstract double fare(double numberOfMiles); public boolean lowerPrice(double numberOfMiles, double amount) { return this.fare(numberOfMiles) < amount; } public boolean cheaperThan(double numberOfMiles, ATaxiVehicle that) { return this.fare(numberOfMiles) < that.fare(numberOfMiles); } }
  • 129. Limo 129 public class Limo extends ATaxiVehicle { private int minRental; public Limo (int minRental, int idNum, int passengers, int pricePerMile) { super (idNum,passengers, pricePerMile); this.minRental = minRental; } public double fare( double numberOfMiles) { if (this.pricePerMile * numberOfMiles< minRental) return this.minRental; else return this.pricePerMile * numberOfMiles; } }
  • 130. Van 130 Back public class Van extends ATaxiVehicle { private boolean access; public Van(boolean access, int idNum, int passengers, int pricePerMile) { super (idNum,passengers, pricePerMile); this.access = access; } public double fare(double numberOfMiles) { return this.pricePerMile * numberOfMiles + this.passengers; } }
  • 131. 5.1.4 Class Diagram 131 ABook # String title # String author # double price # int publicationYear + double salePrice() + boolean cheaperThan(ABook that) + boolean sameAuthor(ABook that) Hardcover + double salePrice() Sale + double salePrice() Paperback + double salePrice()
  • 132. 5.1.4 Solution 132 public abstract class ABook { protected String title; protected String author; protected double price; protected int publicationYear; public ABook(String title, String author, double price, int publicationYear){ this.title =title; this.author = author; this.price = price; this.publicationYear = publicationYear; } public abstract double salePrice(); public boolean cheaperThan(ABook that){ return this.salePrice() < that.salePrice(); } public boolean sameAuthor(ABook that){ return this.author.equals(that.author); } }
  • 133. Hardcover Book 133 public class Hardcover extends ABook { public Hardcover(String title, String author, double price, int publicationYear) { super (title, author, price, publicationYear); } public double salePrice() { return this.price * 0.8; } }
  • 134. Sale Book 134 public class Sale extends ABook { public Sale(String title, String author, double price, int publicationYear) { super(title, author, price, publicationYear); } public double salePrice() { return this.price * 0.5; } }
  • 135. Paperback Book 135 Back public class Paperback extends Abook { public Paperback(String title, String author, double price, int publicationYear) { super(title, author, price, publicationYear); } public double salePrice() { return this.price; } }