Java Reference
In-Depth Information
24.
(You must complete Self-Check Problem 23 before answering this question.)
Add methods called
setFirstName
,
setMiddleInitial
,and
setLastName
to your
Name
class. Give the param-
eters the same names as your fields, and use the
this
keyword in your solution.
25.
How does encapsulation allow you to change the internal implementation of a class?
Section 8.5: Case Study: Designing a Stock Class
26.
What is cohesion? How can you tell whether a class is cohesive?
27.
Why didn't we choose to put the console I/O code into the
Stock
class?
28.
Add accessor methods to the
Stock
class to return the stock's symbol, total shares, and total cost.
Exercises
1.
Add the following method to the
Point
class:
public int manhattanDistance(Point other)
Returns the “Manhattan distance” between the current
Point
object and the given other
Point
object. The
Manhattan distance refers to the distance between two places if one can travel between them only by moving hori-
zontally or vertically, as though driving on the streets of Manhattan. In our case, the Manhattan distance is the sum
of the absolute values of the differences in their coordinates; in other words, the difference in
x
plus the difference in
y
between the points.
2.
Add the following method to the
Point
class:
public boolean isVertical(Point other)
Returns
true
if the given
Point
lines up vertically with this
Point
, that is, if their
x
-coordinates are the same.
3.
Add the following method to the
Point
class:
public double slope(Point other)
Returns the slope of the line drawn between this
Point
and the given other
Point
. Use the formula (
y
2
-
y
1
) / (
x
2
-
x
1
)
to determine the slope between two points (
x
1
,
y
1
) and (
x
2
,
y
2
). Note that this formula fails for points with identical
x
-coordinates, so throw an
IllegalArgumentException
in this case.
4.
Add the following method to the
Point
class:
public boolean isCollinear(Point p1, Point p2)
Returns whether this
Point
is collinear with the given two other
Point
s.
Point
s are collinear if a straight line can be
drawn that connects them. Two basic examples are three points that have the same
x
- or
y
-coordinate. The more gen-
eral case can be determined by calculating the slope of the line between each pair of points and checking whether this
slope is the same for all pairs of points. Use the formula (
y
2
-
y
1
) / (
x
2
-
x
1
) to determine the slope between two points
(
x
1
,
y
1
) and (
x
2
,
y
2
). (Note that this formula fails for points with identical
x
-coordinates so this will have to be a special
case in your code.) Since Java's
double
type is imprecise, round all slope values to a reasonable accuracy such as
four digits past the decimal point before you compare them.
5.
Add the following method to the
TimeSpan
class:
public void add(TimeSpan span)
Adds the given amount of time to this time span.
Search WWH ::
Custom Search