0% found this document useful (0 votes)
130 views

02 - Inheritance and Polymorphism - Subclasses and Methods

The document provides instructions for developing algorithms to solve problems through a 5-step process: 1. Obtain a description of the problem from the client and identify any defects. 2. Analyze the problem to determine the starting point, available data, formulas, and ending point. 3. Develop a high-level algorithm that outlines the major steps to solve the problem without details. 4. Refine the algorithm by adding more details in a process called stepwise refinement. 5. Review the algorithm by walking through each step, checking for simplification opportunities, similarities to other problems, and determining if it solves the original problem. An example problem is provided where a Jeroo must
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
130 views

02 - Inheritance and Polymorphism - Subclasses and Methods

The document provides instructions for developing algorithms to solve problems through a 5-step process: 1. Obtain a description of the problem from the client and identify any defects. 2. Analyze the problem to determine the starting point, available data, formulas, and ending point. 3. Develop a high-level algorithm that outlines the major steps to solve the problem without details. 4. Refine the algorithm by adding more details in a process called stepwise refinement. 5. Review the algorithm by walking through each step, checking for simplification opportunities, similarities to other problems, and determining if it solves the original problem. An example problem is provided where a Jeroo must
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

9/7/21, 1:30 PM 02: Inheritance and Polymorphism: Subclasses and Methods

02: Inheritance and Polymorphism: Subclasses and


Methods

Due
Sep 5 by 11:59pm
Points
100
Submitting
an external tool
Available
until Sep 10 at 11:59pm

The development of an algorithm (a plan) is a key step in solving


a problem. Once we have an algorithm, we can
translate it into a
computer program in some programming language. Our algorithm
development process consists of
five major steps.

2.1.4.2.1. Step 1: Obtain a description of the problem

This step is much more difficult than it appears. In the following


discussion, the word client refers to someone who
wants to
find a solution to a problem, and the word developer refers to
someone who finds a way to solve the
problem. The developer must
create an algorithm that will solve the client’s problem.

The client is responsible for creating a description of the problem,


but this is often the weakest part of the process.
It’s quite common
for a problem description to suffer from one or more of the following
types of defects: (1) the
description relies on unstated assumptions,
(2) the description is ambiguous, (3) the description is incomplete,
or (4)
the description has internal contradictions. These defects are
seldom due to carelessness by the client. Instead, they
are due to the
fact that natural languages (English, French, Korean, etc.) are rather
imprecise. Part of the
developer’s responsibility is to identify
defects in the description of a problem, and to work with the client
to remedy
those defects.

2.1.4.2.2. Step 2: Analyze the problem

The purpose of this step is to determine both the starting and


ending points for solving the problem. This process is
analogous to a
mathematician determining what is given and what must be proven. A
good problem description
makes it easier to perform this step.

When determining the starting point, we should start by seeking


answers to the following questions:

What data are available?

Where is that data?

What formulas pertain to the problem?

What rules exist for working with the data?

What relationships exist among the data values?

When determining the ending point, we need to describe the


characteristics of a solution. In other words, how will we
know when
we’re done? Asking the following questions often helps to determine
the ending point.

https://canvas.vt.edu/courses/135890/assignments/1280223 1/29
9/7/21, 1:30 PM 02: Inheritance and Polymorphism: Subclasses and Methods

What new facts will we have?

What items will have changed?

What changes will have been made to those items?

What things will no longer exist?

2.1.4.2.3. Step 3: Develop a high-level algorithm

An algorithm is a plan for solving a problem, but plans come in


several levels of detail. It’s usually better to start with
a
high-level algorithm that includes the major part of a solution, but
leaves the details until later. We can use an
everyday example to
demonstrate a high-level algorithm.

Problem: I need a send a birthday card to my brother,


Mark.

Analysis: I don’t have a card. I prefer to buy a card rather


than make one myself.

High-level algorithm:

Go to a store that sells greeting cards


Select a card

Purchase a card

Mail the card

This algorithm is satisfactory for daily use, but it lacks details


that would have to be added were a computer to carry
out the solution.
These details include answers to questions such as the following:

“Which store will I visit?”

“How will I get there: walk, drive, ride my bicycle, take the
bus?”

“What kind of card does Mark like: humorous, sentimental,


risqué?”

These kinds of details are considered in the next step of our


process.

2.1.4.2.4. Step 4: Refine the algorithm by adding more detail

A high-level algorithm shows the major steps that need to be


followed to solve a problem. Now we need to add
details to these
steps, but how much detail should we add? Unfortunately, the answer
to this question depends on
the situation. We have to consider who
(or what) is going to implement the algorithm and how much that person
(or
thing) already knows how to do. If someone is going to purchase
Mark’s birthday card on my behalf, my instructions
have to be adapted
to whether or not that person is familiar with the stores in the
community and how well the
purchaser known my brother’s taste in
greeting cards.

When our goal is to develop algorithms that will lead to computer


programs, we need to consider the capabilities of
the computer and
provide enough detail so that someone else could use our algorithm
to write a computer program
that follows the steps in our algorithm.
As with the birthday card problem, we need to adjust the level of
detail to
match the ability of the programmer. When in doubt, or when
you are learning, it is better to have too much detail
than to have
too little.

Most of our examples will move from a high-level to a detailed


algorithm in a single step, but this is not always
reasonable For larger more complex problems it is common to go through this process several times developing
https://canvas.vt.edu/courses/135890/assignments/1280223 2/29
9/7/21, 1:30 PM 02: Inheritance and Polymorphism: Subclasses and Methods
reasonable. For
larger, more complex problems, it is common to go through this
process several times, developing
intermediate level algorithms as
we go. Each time, we add more detail to the previous algorithm,
stopping when we
see no benefit to further refinement. This technique
of gradually working from a high-level to a detailed algorithm is
often called stepwise refinement.

Note

Stepwise refinement is a process


for developing a detailed algorithm by gradually adding detail to a
high-level algorithm.

2.1.4.2.5. Step 5: Review the algorithm

The final step is to review the algorithm. What are we looking for?
First, we need to work through the algorithm step
by step to determine
whether or not it will solve the original problem. Once we are
satisfied that the algorithm does
provide a solution to the problem,
we start to look for other things. The following questions are typical
of ones that
should be asked whenever we review an algorithm. Asking
these questions and seeking their answers is a good way
to develop
skills that can be applied to the next problem.

Does this algorithm solve a very specific


problem or does it
solve a more general problem? If it solves a very
specific problem,
should it be generalized?
For example, an algorithm that computes
the area of a circle having
radius 5.2 meters
(formula π(5.2) ) solves a very specific problem, but an
algorithm that computes the area of
2

any circle
(formula πR ) solves a more general problem.
2

Can this algorithm be simplified?


One formula for computing the perimeter of a rectangle is:

length + width + length + width

A simpler formula would be:

2.0 * (length + width)

Is this solution similar to the solution to


another problem? How are they alike? How are they different?
For
example, consider the following two formulae:

Rectangle area = length * width


Triangle area = 0.5 * base * height

Similarities: Each computes an area. Each multiplies two


measurements.

0.5.
Differences: Different measurements are used. The triangle
formula contains
Hypothesis: Perhaps every area formula involves multiplying two
measurements.

2.1.4.3. Example: Pick and Plant

This section contains an extended example that demonstrates the


algorithm development process. To complete the
algorithm, we need to
know that every Jeroo can hop forward, turn left and right, pick a
flower from its current
location, and plant a flower at its current
location.

2.1.4.3.1. Problem Statement (Step 1)

A Jeroo starts at (0, 0) facing East with no flowers in its pouch.


There is a flower at location (3, 0). Write a program
https://canvas.vt.edu/courses/135890/assignments/1280223 3/29
9/7/21, 1:30 PM ( ) g 02: Inheritance and Polymorphism: Subclasses and Methods ( ) g
that directs the
Jeroo to pick the flower and plant it at location (3, 2). After
planting the flower, the Jeroo should hop
one space East and stop.
There are no other nets, flowers, or Jeroos on the island.

Start

Finish

2.1.4.3.2. Analysis of the Problem (Step 2)

1. The flower is exactly three spaces ahead of the jeroo.

2. The flower is to be planted exactly two spaces South of


its current location.

3. The Jeroo is to finish facing East one space East of the


planted flower.

4. There are no nets to worry about.

2.1.4.3.3. High-level Algorithm (Step 3)

Let’s name the Jeroo Bobby. Bobby should do the following:

Get the flower


Put the flower


https://canvas.vt.edu/courses/135890/assignments/1280223 4/29
9/7/21, 1:30 PM 02: Inheritance and Polymorphism: Subclasses and Methods
Hop East

2.1.4.3.4. Detailed Algorithm (Step 4)

Let’s name the Jeroo Bobby. Bobby should do the following:

Get the flower

Hop 3 times

Pick the flower

Put the flower

Turn right

Hop 2 times

Plant a flower

Hop East

Turn left

Hop once

2.1.4.3.5. Review the Algorithm (Step 5)

1. The high-level algorithm partitioned the problem into three


rather easy subproblems. This seems like a good
technique.

2. This algorithm solves a very specific problem because the


Jeroo and the flower are in very specific locations.

3. This algorithm is actually a solution to a slightly more


general problem in which the Jeroo starts anywhere, and
the flower
is 3 spaces directly ahead of the Jeroo.

2.1.4.3.6. Java Code for “Pick and Plant”

A good programmer doesn’t write a program all at once. Instead,


the programmer will write and test the program in a
series of builds.
Each build adds to the previous one. The high-level algorithm will
guide us in this process.

Note

A good programmer works


incrementally, add small pieces
one at a time and constantly re-checking
the work so far.

2.1.4.3.7. FIRST BUILD

To see this solution in action, create a new BlueJ project


scenario and use the “New Class…” button to
create a new
Island subclass with the name of
your choice. This subclass will hold your new code.

https://canvas.vt.edu/courses/135890/assignments/1280223 5/29
9/7/21, 1:30 PM 02: Inheritance and Polymorphism: Subclasses and Methods
The recommended first build contains three things:

1. The main method (here myProgram() in your island


subclass).

2. Declaration and instantiation of every Jeroo that will


be used.

3. The high-level algorithm in the form of comments.

public void myProgram()

Jeroo bobby = new Jeroo();

this.addObject(bobby, 0, 0);

// --- Get the flower ---

// --- Put the flower ---

// --- Hop East ---

} // ===== end of method myProgram() =====

The instantiation at the beginning of myProgram() places


bobby at (0, 0), facing East, with no flowers.

Once the first build is working correctly, we can proceed to the


others. In this case, each build will correspond to one
step in the
high-level algorithm. It may seem like a lot of work to use four builds
for such a simple program, but doing
so helps establish habits that will
become invaluable as the programs become more complex.

2.1.4.3.8. SECOND BUILD

This build adds the logic to “get the flower”, which in the detailed
algorithm (step 4 above) consists of hopping 3
times and then picking
the flower. The new code is indicated by comments that wouldn’t appear
in the original (they
are just here to call attention to the additions).
The blank lines help show the organization of the logic.

public void myProgram()

Jeroo bobby = new Jeroo();

this.addObject(bobby, 0, 0);

// --- Get the flower ---

bobby.hop(3); // <-- new code to hop 3 times

bobby.pick(); // <-- new code to pick the flower

// --- Put the flower ---

// --- Hop East ---

} // ===== end of method myProgram() =====

By taking a moment to run the work so far, you can confirm whether
or not this step in the planned algorithm works
as expected. Right-click
on your island subclass in BlueJ’s main window and use “new” (the first menu
entry) to
create a new instance
https://canvas.vt.edu/courses/135890/assignments/1280223 6/29
9/7/21, 1:30 PM 02: Inheritance and Polymorphism: Subclasses and Methods
create a new instance.

2.1.4.3.9. THIRD BUILD

This build adds the logic to “put the flower”. New code is indicated
by the comments that are provided here to mark
the additions.

public void myProgram()

Jeroo bobby = new Jeroo();

this.addObject(bobby, 0, 0);

// --- Get the flower ---

bobby.hop(3);

bobby.pick();

// --- Put the flower ---

bobby.turn(RIGHT); // <-- new code to turn right

bobby.hop(2); // <-- new code to hop 2 times

bobby.plant(); // <-- new code to plant a flower

// --- Hop East ---

} // ===== end of method myProgram() =====

2.1.4.3.10. FOURTH BUILD (final)

This build adds the logic to “hop East”.

public void myProgram()

Jeroo bobby = new Jeroo();

this.addObject(bobby, 0, 0);

// --- Get the flower ---

bobby.hop(3);

bobby.pick();

// --- Put the flower ---

bobby.turn(RIGHT);

bobby.hop(2);

bobby.plant();

// --- Hop East ---

bobby.turn(LEFT); // <-- new code to turn left

bobby.hop(); // <-- new code to hop 1 time

} // ===== end of method myProgram() =====

2 1 4 4 Example: Replace Net with Flower


https://canvas.vt.edu/courses/135890/assignments/1280223 7/29
9/7/21, 1:30 PM 02: Inheritance and Polymorphism: Subclasses and Methods
2.1.4.4. Example: Replace Net with Flower

This section contains a second example that demonstrates the


algorithm development process.

2.1.4.4.1. Problem Statement (Step 1)

There are two Jeroos. One Jeroo starts at (0, 0) facing North with
one flower in its pouch. The second starts at (0, 2)
facing East with
one flower in its pouch. There is a net at location (3, 2). Write a
program that directs the first Jeroo
to give its flower to the second
one. After receiving the flower, the second Jeroo must disable the net,
and plant a
flower in its place. After planting the flower, the Jeroo
must turn and face South. There are no other nets, flowers, or
Jeroos
on the island.

Start

Finish

2.1.4.4.2. Analysis of the Problem (Step 2)

1. Jeroo_2 is exactly two spaces behind Jeroo_1.

2. The only net is exactly three spaces ahead of Jeroo_2.

3. Each Jeroo has exactly one flower.


https://canvas.vt.edu/courses/135890/assignments/1280223 8/29
9/7/21, 1:30 PM 02: Inheritance and Polymorphism: Subclasses and Methods

4. Jeroo_2 will have two flowers after receiving one from Jeroo_1.

One flower must be used to disable the net.


The other flower must be planted at the location of the net,


i.e. (3, 2).

5. Jeroo_1 will finish at (0, 1) facing South.

6. Jeroo_2 is to finish at (3, 2) facing South.

7. Each Jeroo will finish with 0 flowers in its pouch. One


flower was used to disable the net, and the other was
planted.

2.1.4.4.3. High-level Algorithm (Step 3)

Let’s name the first Jeroo Ann and the second one Andy.

Ann should do the following:

Find Andy (but don’t collide with him)


Give a flower to Andy (he will be straight ahead)

After receiving the flower, Andy should do the following:

Find the net (but don’t hop onto it)


Disable the net


Plant a flower at the location of the net


Face South

2.1.4.4.4. Detailed Algorithm (Step 4)

Let’s name the first Jeroo Ann and the second one Andy.

Ann should do the following:

Find Andy

Turn around (either left or right twice)


Hop (to location (0, 1))

Give a flower to Andy

Give ahead

Now Andy should do the following:

Find the net

Hop twice (to location (2, 2))

Disable the net

Toss
https://canvas.vt.edu/courses/135890/assignments/1280223 9/29
9/7/21, 1:30 PM 02: Inheritance and Polymorphism: Subclasses and Methods

Plant a flower at the location of the net


Hop (to location (3, 2))


Plant a flower

Face South

Turn right

2.1.4.4.5. Review the Algorithm (Step 5)

1. The high-level algorithm helps manage the details.

2. This algorithm solves a very specific problem, but the


specific locations are not important. The only thing that is
important is the starting location of the Jeroos relative to one
another and the location of the net relative to the
second Jeroo’s
location and direction.

2.1.4.4.6. Java Code for “Replace Net with Flower”

As before, the code should be written incrementally


as a series of builds. Four builds will be suitable for this
problem.
As usual, the first build will contain the main method, the declaration
and instantiation of the Jeroo objects,
and the high-level algorithm in
the form of comments. The second build will have Ann give her flower to
Andy. The
third build will have Andy locate and disable the net. In the
final build, Andy will place the flower and turn East.

2.1.4.4.7. FIRST BUILD

This build creates the main method, instantiates the Jeroos, and
outlines the high-level algorithm. In this example,
the main method
would be myProgram() contained within a subclass of
Island.

public void myProgram()

Jeroo ann = new Jeroo(NORTH, 1);

this.addObject(ann, 0, 0);

Jeroo andy = new Jeroo(1); // default EAST

this.addObject(andy, 0, 2);

// --- Ann, find Andy ---

// --- Ann, give Andy a flower ---

// --- Andy, find and disable the net ---

// --- Andy, place a flower at (3, 2) ---

// --- Andy, face South ---

} // ===== end of method myProgram() =====

https://canvas.vt.edu/courses/135890/assignments/1280223 10/29
9/7/21, 1:30 PM 02: Inheritance and Polymorphism: Subclasses and Methods

2.1.4.4.8. SECOND BUILD

This build adds the logic for Ann to locate Andy and give him a
flower.

public void myProgram()

Jeroo ann = new Jeroo(NORTH, 1);

this.addObject(ann, 0, 0);

Jeroo andy = new Jeroo(1); // default EAST

this.addObject(andy, 0, 2);

// --- Ann, find Andy ---

ann.turn(LEFT);

ann.turn(LEFT);

ann.hop();

// Now, Ann is at (0, 1) facing South, and Andy is directly ahead

// --- Ann, give Andy a flower ---

ann.give(AHEAD); // Ann now has 0 flowers, Andy has 2

// --- Andy, find and disable the net ---

// --- Andy, place a flower at (3, 2) ---

// --- Andy, face South ---

} // ===== end of method myProgram() =====

2.1.4.4.9. THIRD BUILD

This build adds the logic for Andy to locate and disable the net.

public void myProgram()

Jeroo ann = new Jeroo(NORTH, 1);

this.addObject(ann, 0, 0);

Jeroo andy = new Jeroo(1); // default EAST

this.addObject(andy, 0, 2);

// --- Ann, find Andy ---

ann.turn(LEFT);

ann.turn(LEFT);

ann.hop();

// Now, Ann is at (0, 1) facing South, and Andy is directly ahead

// --- Ann, give Andy a flower ---

ann.give(AHEAD); // Ann now has 0 flowers, Andy has 2

// --- Andy, find and disable the net ---

andy.hop(2); // Andy is at (2, 2) facing the net

andy.toss();

https://canvas.vt.edu/courses/135890/assignments/1280223 11/29
9/7/21, 1:30 PM 02: Inheritance and Polymorphism: Subclasses and Methods
y ();

// --- Andy, place a flower at (3, 2) ---

// --- Andy, face South ---

} // ===== end of method myProgram() =====

2.1.4.4.10. FOURTH BUILD (final)

This build adds the logic for Andy to place a flower at (3, 2) and
turn South.

public void myProgram()

Jeroo ann = new Jeroo(NORTH, 1);

this.addObject(ann, 0, 0);

Jeroo andy = new Jeroo(1); // default EAST

this.addObject(andy, 0, 2);

// --- Ann, find Andy ---

ann.turn(LEFT);

ann.turn(LEFT);

ann.hop();

// Now, Ann is at (0, 1) facing South, and Andy is directly ahead

// --- Ann, give Andy a flower ---

ann.give(AHEAD); // Ann now has 0 flowers, Andy has 2

// --- Andy, find and disable the net ---

andy.hop(2); // Andy is at (2, 2) facing the net

andy.toss();

// --- Andy, place a flower at (3, 2) ---

andy.hop();

andy.plant();

// --- Andy, face South ---

andy.turn(RIGHT);

} // ===== end of method myProgram() =====

2.1.4.5. Self-Check

Practicing Class Hierarchy and Inheritance Current score: 3 out of

3
 

Whi h f th f ll i i NOT t
https://canvas.vt.edu/courses/135890/assignments/1280223
t id h d i i l ith ? 12/29
9/7/21, 1:30 PM 02: Inheritance and Polymorphism: Subclasses and Methods
Which of the following is NOT a step to consider when designing an algorithm? Answer

Create a high-level algorithm Check Answer

Get a problem description


Need help?
Consider the problem and ask additional questions
I'd like a hint
All of these are steps

2.1.5. Creating and Using Jeroo Methods

For some problems, it would be convenient if we could extend


the basic behaviors of Jeroos (or other objects). Java
allows us
to write programmer-defined methods that extend the behavior of
every object created from a given class.

2.1.5.1. Creating and Using a Jeroo Method

The concepts of behavior and method were defined


earlier and are repeated here. A
behavior is an action that an
object can take or a
task that it can perform in response to a request from an external
source. A method is a
collection of statements that
are written in some programming language to describe a specific
behavior.

https://canvas.vt.edu/courses/135890/assignments/1280223 13/29
9/7/21, 1:30 PM 02: Inheritance and Polymorphism: Subclasses and Methods

These definitions imply that the creation of a method is a two-part


process. First, we need to define and name the
new behavior. Second,
we need to write the source code for the method.

2.1.5.1.1. Defining a Behavior

The first question we must ask is “How do I decide on a good


behavior?” There is no fixed answer to this question,
but there are
some guidelines to follow.

1. Examine the high-level algorithm. Any complex, but


well-defined, step is a candidate for a new behavior,
especially
if two or more Jeroos need to perform that step.

2. Examine the detailed-algorithm. Any sequence of steps that


occur several times is a candidate for a new
behavior.

These guidelines serve as a starting point, but experience is a


good teacher. Examine your own programs and those
of others. A good
behavior has a very clear definition and is used more than once in the
program.

2.1.5.1.2. Writing a Jeroo Method

A Jeroo method contains the source code that describes what an


arbitrary Jeroo needs to do to carry out the
corresponding behavior.
The form of a Jeroo method is:

The methodIdentifier on the first line (the header line) is


a name that the programmer chooses for the method. The
name should
indicate the corresponding behavior. The rules for creating an
identifier for a method are the same as
those given in
Module 1–but remember that we always start
method names with a lowercase letter. In every
method,
we should indent every line between the opening and closing braces.

Note

The name of a method should be a verb or a short verb phrase that describes what the method14/29
https://canvas.vt.edu/courses/135890/assignments/1280223
9/7/21, 1:30 PM 02: Inheritance and Polymorphism: Subclasses and Methods
The name of a method should be a
verb or a short
verb phrase that describes what
the method
does.

Since a Jeroo method defines a behavior that applies to every Jeroo,


we cannot send a message to a specific
Jeroo. Instead, we use the
special Java name this, which
is like a pronoun that refers to the Jeroo that is performing
the
entire method.

2.1.5.1.3. Example: Turn Around

If we wanted to add a method to cause a Jeroo to turn around, we


need a class to place it in. We have to create our
own subclass of
Jeroo to hold our code. In BlueJ, you can use the “New Class…”
button to create a new subclass
of Jeroo
with a name of your own choosing. In that new subclass, you could add
a method to turn the jeroo around:

// ----------------------------------------------------------

/**

* Turn the jeroo around 180 degrees so it faces the opposite

* direction.

*/

public void turnAround()

this.turn(LEFT);

this.turn(LEFT);

2.1.5.1.4. Example: One Method Can Use Another, or Even Itself

This example introduces two new behaviors: planting four flowers


in a row, and planting two adjacent rows with four
flowers per row.

// ----------------------------------------------------------

/**

* Plant four flowers in a row, starting at the current location.

*/

public void plantFour()

this.plant(); // -- one ---

this.hop();

this.plant(); // -- two ---

this.hop();

this.plant(); // -- three ---

this.hop();

this.plant(); // -- four ---

// ----------------------------------------------------------
https://canvas.vt.edu/courses/135890/assignments/1280223 15/29
9/7/21, 1:30 PM 02: Inheritance and Polymorphism: Subclasses and Methods
// ----------------------------------------------------------

/**

* Plant two adjacent rows of flowers.

*/

public void plantRowsOfFour()

// --- Plant first row ---

this.plantFour();

// --- Move into position for next row ---

this.turn(RIGHT);

this.hop();

this.turn(RIGHT);

// --- Plant second row (in opposite direction) ---

this.plantFour();

2.1.5.1.5. Using a Jeroo Method

A Jeroo method is used just like any other method. In our island’s
myProgram() method, we just have to be sure to
create
a jeroo from our special subclass that contains the new methods we
want to use. Then we send a message
to a specific Jeroo object,
requesting that Jeroo to perform the task associated with the method.

As an example, suppose we had created our own Jeroo


subclass called PlantingJeroo, and added the
plantFour() and plantRowsOfFour() methods
to it. Then in our island subclass, we could have a new Jeroo
named
Ali plant two rows of flowers, south and east of (5, 5):

public void myProgram()

PlantingJeroo ali = new PlantingJeroo(8);

this.addObject(ali, 5, 5);

ali.plantRowsOfFour();

2.1.5.1.6. A Word About Constructors

We know
that when we create a subclass
that it inherits all of the
methods and attributes from the class that it
extends. If you create a
subclass of Jeroo called PlantingJeroo, then
any PlantingJeroo object can perform
all of the methods
that any Jeroo knows–because a PlantingJeroo
is a special kind of Jeroo. The
PlantingJeroo
class inherits all of
the methods and attributes from the class Jeroo, and also
understands any
new ones you write, such as the
platRowsOfFour() method. Computer scientists sometimes
call this an is-a
relationship,
because every PlantingJeroo object is a
Jeroo at the same time–just a Jeroo that can do more.

Note

An is-a relationship exists


between a subclass and its superclass, since every instance of the
subclass is also an instance of the superclass at the same time.
https://canvas.vt.edu/courses/135890/assignments/1280223 16/29
9/7/21, 1:30 PM 02: Inheritance and Polymorphism: Subclasses and Methods

Also, as we have already read above, a constructor is a special


kind of method that is used to initialize a brand new
object. But,
while a subclass automatically inherits all of the (plain) methods
and attributes from its superclass, it
does not inherit
constructors. That means that the object instantiation for
Ali in the previous example will not actually
compile–unless we
provide an appropriate constructor for our
PlantingJeroo subclass.

One reason that subclasses do not automatically inherit constructors


is because subclasses can add new attributes
in addition to new methods,
and those attributes must be initialized, no matter what.
But any constructor from a
superclass won’t know anything about the
subclass’ new attributes and can’t initialize them appropriately. So
subclasses have to explicitly define every constructor they support,
all the time.

Note

Every time you create a subclass, you are responsible for defining
all of the constructors it supports.
Constructors are not
inherited from superclasses.

Fortunately, while constructors are not inherited, there is a


simple pattern for defining them. In our PlantingJeroo,
we can add the following constructor:

// ----------------------------------------------------------

/**

* Create a new Jeroo facing east.

* @param flowers The number of flowers the Jeroo is holding.

*/

public PlantingJeroo(int flowers)

super(flowers);

While we have not yet covered all of the features in this small
piece of code, the gist is straightforward. A constructor
is
declared like a regular method, except that
we omit the word void
and its name is exactly the same as the class
name.
Here, we are defining a constructor for our
PlantingJeroo subclass that takes one number (integer)
as an
argument, representing the number of flowers in its pouch.

The body of this constructor contains only a single line that uses
the special Java keyword super. This word can
only
be used as the first word inside a subclass constructor, and it allows
us to invoke a superclass constructor,
passing it any information it
might need. So here, we are saying that the first (and only) action
in our
PlantingJeroo constructor is to call the
constructor for its superclass (Jeroo), passing the
number of flowers.
This allows the superclass
to initialize all of its attributes correctly with the given information.
If our subclass needed
more initialization, we would perform that in
following statements in the subclass constructor’s body.

But for now, this constructor is enough for our


PlantingJeroo class. It will allow us to create a
PlantingJeroo
object by specifying its location and
number of flowers. That will in turn allow us to instantiate the
Ali Jeroo in the
previous example without problems.

2.1.5.2. Preconditions and Postconditions


https://canvas.vt.edu/courses/135890/assignments/1280223 17/29
9/7/21, 1:30 PM 02: Inheritance and Polymorphism: Subclasses and Methods

We should always define a behavior carefully before we write the


code for the corresponding method. A complete
definition for a
behavior must include a statement of the preconditions and the
postconditions.
A precondition for a
method is
something that is assumed to be true before the method is invoked. The
portion of the code that invokes
the method is responsible for ensuring
that all preconditions are satisfied before the method is invoked.
A
postcondition for a method is
something that is true after the method has been executed. The code
within the
method is responsible for ensuring that all postconditions
are met.
The process of determining good preconditions
and postconditions can
be difficult, but it is easier if we remember a few characteristics of
objects and methods.

1. All work is done by sending messages to objects.

2. Exactly one object executes a method in response to a


message.

3. A method can modify the attributes of the object that


executes the method, but cannot directly modify the
attributes of
any other object.

4. One method can send messages to several different objects,


and those messages can lead to modifications in
their
receivers.

Using the previous list of characteristics as a guide, we can use


the following questions as a basis for writing
preconditions and
postconditions. When we are working with Jeroos, we need to consider
how a method can
change the attributes of the Jeroo object that executes
the method. In some cases, Jeroo actions like pick(),
plant(), and toss() can change the attributes
of the world by adding or removing objects, although we normally
don’t
send messages to these other objects directly. Behind the scenes,
the pick(), plant(), and
toss()
methods send appropriate messages to the island in
order to add or remove objects corresponding to the desired
behavior.

Precondition Questions Postcondition Questions


Do any of the attributes of the receiving object need How does this method affect the attributes of
to have special values? the receiving
object?

Location Location
Direction
Direction

Flowers
Flowers

Are the contents of certain island cells important?


Have the contents of any island cells changed?

The preconditions and postconditions can be created rather


informally, but the final versions should be
stated in a comment block
at the beginning of the source code for the method. As an example,
consider
the method from the previous section to plant four flowers
in a row:

// ----------------------------------------------------------

/**

* Plant four flowers in a row, starting at the current location.

*
* @precondition The three spaces directly ahead of the Jeroo are clear.

* @precondition The Jeroo has at least four flowers.

* @postcondition The Jeroo has planted four flowers, starting at its

* current location and proceeding straight ahead.

* @postcondition The Jeroo is standing on the last flower and facing in


https://canvas.vt.edu/courses/135890/assignments/1280223 18/29
9/7/21, 1:30 PM 02: Inheritance and Polymorphism: Subclasses and Methods
* @postcondition The Jeroo is standing on the last flower, and facing in

* its original direction.

*/

public void plantFour()

this.plant(); // -- one ---


this.hop();

this.plant(); // -- two ---


this.hop();

this.plant(); // -- three ---

this.hop();

this.plant(); // -- four ---

2.1.5.3. Example: Clear Nets and Pick

The section contains an extended example that demonstrates the


algorithm development process, and
shows a recommended process for
developing source code that contains Jeroo methods.

2.1.5.3.1. Problem Statement (Step 1)

A Jeroo starts at (4, 1) facing North with 5 flowers in its pouch.


There are two nets immediately South of
the Jeroo at locations (4, 2)
and (4, 3). There is a flower directly South of the second net. Write
a
program that directs the Jeroo to disable the nets and pick the flower.
After picking the flower, the Jeroo
should return to its starting
location and face South.

Start

Finish
https://canvas.vt.edu/courses/135890/assignments/1280223 19/29
9/7/21, 1:30 PM 02: Inheritance and Polymorphism: Subclasses and Methods

2.1.5.3.2. Analysis of the Problem (Step 2)

1. The Jeroo must turn around to locate the first net

2. Each net is directly South of the previous one

3. The first net is directly South of the Jeroo

4. The flower is at location (4, 4)

5. The Jeroo must finish facing South at location (4, 1)

6. The Jeroo should finish with 5 - 2 + 1 = 4 flowers

2.1.5.3.3. Detailed Algorithm (Steps 3 and 4)

Let’s name the Jeroo Kim. Kim should do the following:

Turn around // now at (4, 1) facing South|br|


Disable two nets in a row

Toss

Hop once // now at (4, 2) facing South


Toss

Hop once // now at (4, 3) facing South

Get the flower

Hop once // now on flower at (4, 4) facing South


Pick

Go back to (4, 1) and turn around

Turn around // now at (4, 4) facing North


https://canvas.vt.edu/courses/135890/assignments/1280223 20/29
9/7/21, 1:30 PM 02: Inheritance and Polymorphism: Subclasses and Methods
Turn around // now at (4, 4) facing North

Hop 3 times // now at (4, 1) facing North


Turn around // now at (4, 1) facing South

2.1.5.3.4. Review the Algorithm (Step 5)

1. The high-level algorithm helps manage the details.

2. We used a “turn around” step in example 4.2. We can use the


same logic here.

3. The act of turning around appears as a step in the high-level


algorithm and as part of the “Go back to
(4, 1) and turn around”
step. Interesting!

2.1.5.3.5. Possible Behaviors

1. “Turn around” is used three times

2. The sequence “Toss, Hop” is used two times in the “Disable


nets” step.

We will create a custom Jeroo subclass and write a


Jeroo method for each of these behaviors, but first,
we need to define
a purpose, preconditions, and postconditions for each method. This can
be done
informally, because we will write these things in a comment
block at the beginning of each method.

Note

Method: turnAround()

Purpose: Make the Jeroo turn 180 degrees


Preconditions:

none

Postconditions:

The Jeroo has turned 180 degrees


The Jeroo is at the same location

Note

Method: tossAndHop()

Purpose: Disable a net and move to the newly cleared location


Preconditions:

https://canvas.vt.edu/courses/135890/assignments/1280223 21/29
9/7/21, 1:30 PM 02: Inheritance and Polymorphism: Subclasses and Methods
There is a net ahead

The Jeroo has at least one flower

Postconditions:

The net has been disabled


The Jeroo has one less flower


The Jeroo is at the location originally occupied by the net


The Jeroo has not changed direction

The last postcondition of the tossAndHop() method simply


says that the Jeroo is facing the direction it
was facing at the start
of the method. It does not prohibit the Jeroo from changing direction
during the
course of the method as long as the Jeroo returns to its
original direction at the end.

2.1.5.3.6. Java Code for “Clear Nets and Pick”

As before, we should develop the code as a series of builds. To


start this process, create a new project
using BlueJ
use the “New Class…” button to create a new subclass of Island called
ClearNetsAndPick for this example. Also, create a
new subclass of Jeroo called ClearingJeroo
to
hold your Jeroo methods.
Once you have these classes created, make sure they are compiled.
Edit the
constructor provided in your ClearNetsAndPick class
to create and add flowers and nets at the
appropriate starting
locations on the island.
Then right-click on your ClearNetsAndPick class and
create an instance of it, which will then fill the world view.

2.1.5.3.7. FIRST BUILD

The recommended first build contains three things:

1. The myProgram() method in your island subclass


that creates and sends messages to the Jeroo.

2. Declaration and instantiation of every Jeroo that will be


used. This implies adding an appropriate
constructor to our
Jeroo subclass.

3. The high-level algorithm in the form of comments.

4. Skeletons for each of the Jeroo methods in your Jeroo


subclass. These skeletons are often called
stubs.

Note

A method stub, or just a


stub, is a bare skeleton of
a method that will compile, but is
really just a placeholder for
the real method definition that will come later.
https://canvas.vt.edu/courses/135890/assignments/1280223 22/29
9/7/21, 1:30 PM 02: Inheritance and Polymorphism: Subclasses and Methods

The myProgram() method goes inside your


ClearNetsAndPick class:

public void myProgram()

Jeroo kim = new Jeroo(NORTH, 5);

this.addObject(kim, 4, 1);

// --- Turn around ---

// --- Disable nets ---

// --- Get the flower ---

// --- Go back to (4, 1) and turn around ---

An appropriate constructor and the new Jeroo methods go inside your


ClearingJeroo class:

// ----------------------------------------------------------

/**

* Create a new Jeroo.

* @param direction The direction the Jeroo is facing.

* @param flowers The number of flowers the Jeroo is holding.

*/

public Jeroo(CompassDirection direction, int flowers)

super(direction, flowers); // Let the superclass initialize these

// ----------------------------------------------------------

/**

* Turn the jeroo around 180 degrees so it faces the opposite

* direction.

*
* @precondition None.

*
* @postcondition The Jeroo has turned 180 degrees.

* @postcondition The Jeroo is at the same location.

*/

public void turnAround()

https://canvas.vt.edu/courses/135890/assignments/1280223 23/29
9/7/21, 1:30 PM 02: Inheritance and Polymorphism: Subclasses and Methods

// ----------------------------------------------------------

/**

* Disable a net and move to the newly cleared location.

*
* @precondition There is a net ahead.

* @precondition The Jeroo has at least one flower.

*
* @postcondition The net has been disabled.

* @postcondition The Jeroo has one less flower.

* @postcondition The Jeroo is at the location originally occupied by the ne


* @postcondition The Jeroo has not changed direction.

*/

public void tossAndHop()

2.1.5.3.8. SECOND BUILD

This build finishes the turnAround() method and uses it


in the myProgram() method. It would be
wise to test this
method four times, each time start with Kim facing in a different
direction. Once we are
comfortable that this method works correctly, we
can proceed with the next build.

In the ClearNetsAndPick class:

public void myProgram()

Jeroo kim = new Jeroo(NORTH, 5);

this.addObject(kim, 4, 1);

// --- Turn around ---

kim.turnAround(); // new code

// --- Disable nets ---

// --- Get the flower ---

// --- Go back to (4, 1) and turn around ---

In the ClearingJeroo class:

// ----------------------------------------------------------

/**

* Turn the jeroo around 180 degrees so it faces the opposite


https://canvas.vt.edu/courses/135890/assignments/1280223 24/29
9/7/21, 1:30 PM 02: Inheritance and Polymorphism: Subclasses and Methods
* Turn the jeroo around 180 degrees so it faces the opposite

* direction.

*
* @precondition None.

*
* @postcondition The Jeroo has turned 180 degrees.

* @postcondition The Jeroo is at the same location.

*/

public void turnAround()

this.turn(LEFT); // new code

this.turn(LEFT); // new code

// ----------------------------------------------------------

/**

* Disable a net and move to the newly cleared location.

*
* @precondition There is a net ahead.

* @precondition The Jeroo has at least one flower.

*
* @postcondition The net has been disabled.

* @postcondition The Jeroo has one less flower.

* @postcondition The Jeroo is at the location originally occupied by the ne


* @postcondition The Jeroo has not changed direction.

*/

public void tossAndHop()

2.1.5.3.9. THIRD BUILD

This build finishes the tossAndHop() method and uses it


in the myProgram() method. Our focus is on
destroying the
two nets.

In the ClearNetsAndPick class:

public void myProgram()

Jeroo kim = new Jeroo(NORTH, 5);

this.addObject(kim, 4, 1);

// --- Turn around ---

kim.turnAround();

// --- Disable nets ---

ki t A dH ()
https://canvas.vt.edu/courses/135890/assignments/1280223 // d 25/29
9/7/21, 1:30 PM 02: Inheritance and Polymorphism: Subclasses and Methods
kim.tossAndHop(); // new code

kim.tossAndHop(); // new code

// --- Get the flower ---

// --- Go back to (4, 1) and turn around ---

In the ClearingJeroo class:

// ----------------------------------------------------------

/**

* Turn the jeroo around 180 degrees so it faces the opposite

* direction.

*
* @precondition None.

*
* @postcondition The Jeroo has turned 180 degrees.

* @postcondition The Jeroo is at the same location.

*/

public void turnAround()

this.turn(LEFT);

this.turn(LEFT);

// ----------------------------------------------------------

/**

* Disable a net and move to the newly cleared location.

*
* @precondition There is a net ahead.

* @precondition The Jeroo has at least one flower.

*
* @postcondition The net has been disabled.

* @postcondition The Jeroo has one less flower.

* @postcondition The Jeroo is at the location originally occupied by the ne


* @postcondition The Jeroo has not changed direction.

*/

public void tossAndHop()

this.toss(); // new code

this.hop(); // new code

2.1.5.3.10. FOURTH BUILD (final)


https://canvas.vt.edu/courses/135890/assignments/1280223 26/29
9/7/21, 1:30 PM
( ) 02: Inheritance and Polymorphism: Subclasses and Methods

This build finishes the myProgram() method. We need


to check to see that Kim has the correct number
of flowers at the
end.

In the ClearNetsAndPick class:

public void myProgram()

Jeroo kim = new Jeroo(NORTH, 5);

this.addObject(kim, 4, 1);

// --- Turn around ---

kim.turnAround();

// --- Disable nets ---

kim.tossAndHop();

kim.tossAndHop();

// --- Get the flower ---

kim.hop(); // new code

kim.pick(); // new code

// --- Go back to (4, 1) and turn around ---

kim.turnAround(); // new code

kim.hop(3); // new code


kim.turnAround(); // new code

2.1.5.4. Self-Check

Practicing Methods Current score: 3 out of

3
 

What is the method identifier in the following method definition? Answer

public int add3Ints(int a, int b, int c)


Check Answer
{

return a + b + c;

} Need help?
I'd like a hint
return

https://canvas.vt.edu/courses/135890/assignments/1280223 27/29
9/7/21, 1:30 PM 02: Inheritance and Polymorphism: Subclasses and Methods
public

int

add3Ints

a+b+c

2.1.6. Syntax Practice 2b: Subclass Constructors

Syntax Practice 2b: Subclass Cons… X857: King subclass


11% You are writing a declaration for a new class called King
that represe
been started
for you below. Assuming that the class ChessPiece is a
declaration to indicate that King
is a subclass of ChessPiece (do no

X857: King subclass (/gym/exe…
which should remain blank for this question).

Your Answer: Fee
You are writing a declaration
for a new class called King 1.0
/
that represents a chess piec… 1.0
Java (/gym/exercises/search?s… 1 public class King extends ChessPiece
2 { 1.0
/
1.0
3 }

X858: Jeroo with 8 flowers (/g…
 4 Resu
You are writing a subclass of
Jeroo called RichJeroo 0
/ 1.0
and the constructor appear… 
Java (/gym/exercises/search?s…
https://canvas.vt.edu/courses/135890/assignments/1280223 28/29
9/7/21, 1:30 PM 02: Inheritance and Polymorphism: Subclasses and Methods


X859: Jeroo facing SOUTH wit…

You are writing a subclass of
Jeroo called SunnyJeroo 0
/ 1.0
and the constructor appear… Check my answer!
Reset

Java (/gym/exercises/search?s…
Next exercise (/gym/exercises/858/practice?lti_launch=true&workout_id=1343

https://canvas.vt.edu/courses/135890/assignments/1280223 29/29

You might also like