Title: Creating Class Behaviors
1Creating Class Behaviors
- In the Robot world 1 mile 8 blocks
- Suppose we want a robot to run a marathon (26
miles)? - Does our program have to have (26) 8 move()
statements? - Wouldnt it be nice to tell a robot to run a
marathon - Karel.runMarathon()
2Building a Marathon-Running Robot
- Let us build a robot to run a marathon
- If we define a moveMile() behavior as eight
move() messages - we can reduce the size of our program by (26)
8 / 8 or down to 26 instructions - Can we do better than these 26 instructions?
- we can specify as many behaviors as we need for a
class of robots - Can we think of other behaviors to further
simplify the problem? - HAS A relationships
- Marathon Robot HAS A move mile behavior or
characteristic (that is different from a ur-Robot)
3Defining New Classes of Robots
- To build a new class of robots, we include a
class specification in a new file of our program - The general form of this specification
- class ltnew-class-namegt extends ltold-class-namegt
-
- ltlist-of-new-methodsgt
4Specification Details
- Reserved Words and symbols
- class
- extends
- braces
- We must replace the elements in angle brackets lt
gt appropriately - ltnew-class-namegt what do we call this new type of
robot? - ltold-class-namegt what old robot to add features
to? - ltlist-of-new-methodsgt list of new features
5Naming Things
- In developing the names for robots and new
methods - any uppercase and lowercase letters A..Z, a..z,
digits 0..9, and underscore _ can be used - unique name to the program
- does not match any reserved words
- must begin with a letter
- typically upper case for a class
- lower case for a method or instruction
6Specifying a Marathon Robot
- class MarathonRobot extends Robot
-
- void moveMile()
-
- // instructions omitted for now
-
- // other instructions
7extends Robot?
- class MarathonRobot extends Robot
- we indicate the MarathonRobot inherits all the
capabilities of the Robot class - in other words MarathonRobot knows all about
move(), turnLeft(), pickBeeper(), putBeeper(),
and shutOff() - Robot is the base class of MarathonRobot
- MarathonRobot is a derived class of Robot
- IS-A relationship
- MarathonRobot IS A ur-Robot
8Defining new methods in a program
- Download Stair SweeperDemo
- Verify this program is correct by tracing the
code before running it
9Robot Program Format
- We use at least two files in creating new robots
and robot methods - The Main Class file which is where the robot is
constructed and given its task - The Main Class is defined, the world is accessed,
the speed is set - The robot is constructed and receives its task
instructions in the task() method - The second file contains the description of the
new robot, and the definition of its methods - A constructor which describes how we build the
robot - And the definitions of the new instructions
10Main Class
- public class Main implements Directions
- public static void task()
- Stair_Sweeper Karel new Stair_Sweeper(1, 1,
East, 0) - Karel.climbStair()
- Karel.pickBeeper()
- // other instructions
- Karel.turnOff()
-
- // Main entry point
- static public void main(String args)
- World.setDelay(20)
- World.readWorld("stairs.txt")
- task()
-
11Class Header Main
- public class Application implements Directions
- // details of the class specification here
-
- Name of class will be same as the name of the
file, with a .java suffix - This class is contained in the file Main.java
- Capitalization counts
- Directions is an interface that is is implemented
by Main - In other words Main fleshes out the details of
Directions - Main has the remaining details specific to the
particular task the robot has to perform
12StairSweeper class
- class Stair_Sweeper extends Robot
- // constructor
- public Stair_Sweeper(int street, int avenue,
- Directions.Direction dir, int count)
- super(street, avenue, dir, count)
- //methods
- public void turnRight()
- turnLeft()
- turnLeft()
- turnLeft()
-
-
- public void climbStair()
- turnLeft() move()
- turnRight() move()
-
13Class header StairSweeper
- class Stair_Sweeper extends Robot
-
- Name of class will be same as the name of the
file, with a .java suffix - This class is specified in the file
StairSweeper.java - The StairSweeper robot inherits information and
extends the capabilities of the Robot robot - Everything a Robot can do, a StairSweeper can do
- move(), turnLeft(), pickBeeper(), putBeeper(),
turnOff() - But a StairSweeper will be able to do more (have
more features)
14Constructing a new robot
- public Stair_Sweeper(int street, int avenue,
- Directions.direction dir, int count)
-
- super(street, avenue, dir, count)
-
- This specifies how a robot is to be constructed
- Go back and look at the main()
- The instruction new Stair_Sweeper(1, 1, East, 0)
is using this method, known as a constructor - We are specifying location, direction, and number
of beepers - A constructor has the same name as the class
- The super keyword is indicating that this object
is to be built the same way as its parent, Robot - Our robot constructors will always look like this
at the beginning
15New robot methods
- public void turnRight()
- turnLeft()
- turnLeft()
- turnLeft()
-
-
- public void climbStair()
- turnLeft()
- move()
- turnRight()
- move()
-
- public is a modifier letting us know that we can
access this method from outside the class (in
main() for example) - Notice that climbStair() can use turnRight() as
part of its definition - The method headers are known as signatures (name
and paramter list) - All of the signatures of a class are known as the
class interface or API - Interface vs. interface?
16Advantages of building new robots
- Structure problem solutions
- Programs become easier to understand and read
- Lead to fewer errors
- Enable future modifications
- Debugging programs is easier
- New instructions can be tested independently
- New instructions impose structure, which makes it
easier to find bugs
17Conditionals
- How do we solve tasks in which every particular
of a task is not specifically known? - A robot needs the ability to survey its immediate
environment and make decisions about what to do
next - The IF and the IF/ELSE provide robots with
decision making abilities - Robot programs contain several different kinds of
instructions - Messages to robots, either primitives or new
instructions - Constructors (specifications on how to build a
robot) - Control statements IF and IF/ELSE are the first
examples of these
18The IF instruction
- General form
- if ( lttestgt )
-
- ltinstruction-listgt
-
- Robot determines whether lttestgt is true or false
- ltinstruction-listgt is a sequence of any valid
robot commands that will be performed when the
robot determines the lttestgt is true - Nothing will happen when the lttestgt is false
19Example of IF statement
- // in a method // in a main task block
- if (nextToABeeper()) if (Karel.nextToABeeper(
)) -
- pickBeeper() Karel.pickBeeper()
-
- turnLeft() Karel.turnLeft()
- A beeper will be picked up only if there is a
beeper on the same corner as the robot - Dependent upon the results of the test
- The robot will turn left, regardless of whether a
beeper is on the corner or not - Independent of the results of the test
20Conditions that a robot can test
- class Robot extends Robot
-
- boolean frontIsClear()
- boolean nextToABeeper()
- boolean nextToARobot()
- boolean facingNorth()
- boolean facingSouth()
- boolean facingEast()
- boolean facingWest()
- boolean anyBeepersInBeeperBag()
- boolean isVisible()
-
- // notice we are checking the state of the
robot - // we can also use accessors to build our own
tests
21Negative conditions?
- Suppose we want a negative form of a predicate?
- We can precede a predicate with the negative
operator ! - if (! Karel.next-To-A-Beeper())
-
- // stuff
-
22For practice two methods
- public void faceNorth()
-
- public void faceNorthIfFacingSouth()
23The IF/ELSE instruction
- General form
- if ( lttestgt ) // note lack of semicolon
- ltinstruction-list-1gt
- else // note lack of semicolon
- ltinstruction-list-2gt
-
- Robot determines whether lttestgt is true or false
- ltinstruction-list-1gt is a sequence of any valid
robot commands that will execute when the robot
determines the lttestgt is true - ltinstruction-list-2gt will execute when the lttestgt
is false
24Racer Robot
- A hurdle jumping race
- A robot will run a mile. The course may or may
not have an obstacle (wall) in the path. If the
robot encounters a wall, it will go around
(hurdle) the wall. Otherwise it will continue on
its path - Download Sprinter demo
25Nested IF Instructions
- Written with an IF instruction nested inside the
THEN or ELSE clause of another IF - As an example
- if ( lttestgt )
- if ( lttestgt )
- ltinstruction-list-1gt
- else ltinstruction-list-2gt
-
- else
- ltinstruction-list-2gt
-
26New predicate instructions
- We could create a new subclass of the robot class
and provide a new predicate method - class myRobot extends Robot
- // assume constructor
- boolean frontIsBlocked()
-
- return ! frontIsCLear()
-
- // more stuff
-
27Use of the new predicate
- public static void main(String args)
-
- myRobot R new myRobot(1, 1, North, 0)
- if (R.frontIsBlocked())
-
- // stuff
-
- // and so on
-
28Walls to the right or left?
- Suppose we needed to determine if there is a wall
to the right or left? - public boolean leftIsClear()
-
- turnLeft()
- if (frontIsClear())
-
- turnRight() // assume definition
- return true // method terminates here
-
- turnRight()
- return false
-
- Return statement immediately terminates the method
29When to Use an IF Instruction
- The IF instruction allows a robot to decide
whether to execute or skip entirely the block of
instructions within the THEN clause - The IF/ELSE instruction allows a robot to decide
whether to execute or skip the block of
instructions within the THEN clause or the ELSE
clause - Nesting these instructions allows robots to make
more complex choices
30Loops
- We have already seen instances where a robot
needs to repeat instructions to perform a task - turnRight()
- moveMile()
- By defining new instructions we can minimize
repetitive instructions - runMarathon()
31Loops for known number of repetitions
- There are times when you know how many times an
instruction needs to be repeated - turnRight() is always 3 left turns
- moveMile() is always 8 moves()
- Method turnRight() with a loop
- void turnRight()
- for (int count 0 count lt 3 count)
- turnLeft()
-
-
32FOR loop General form
- for (int count 0 count lt ltnumberOfTimesgt
count) - ltinstruction-listgt
-
- int count count is the name of a variable that
stores integers (whole numbers) its initial
value is 0 - count lt ltnumberOfTimesgt as long as the current
value of count is less than the number of loops
we want, we keep looping - count will be equal to the number of loops we
wanted when the loop is finished - count we increment (add 1 to) the value of
count - ltinstructionsgt Any valid robot instructions,
including other loops
33FOR loop What does this do?
-
- void whatDoIDo()
- for (int count 0 count lt 4 count)
- for (int count2 0 count2 lt 6 count2)
- move()
-
- turnLeft()
-
-
34An unknown number of repetitions
- Suppose we know we want a robot to repeat a
series of instructions, but we do not know how
many times - Task There is a beeper somewhere on the same
street in front of the robot, but we do not know
exactly where How does the robot find the
beeper? - FOR loop requires an upper limit (and there is no
guarantee the beeper will fall within the range) - IF statements are a one-time execute statement
- We need something to combine the testing ability
of the IF statement with the iteration of a FOR
loop
35WHILE loop General form
- while ( lttestgt )
- ltinstruction-listgt
-
- Reserved word while starts the instruction,
parentheses enclose the lttestgt , and braces
enclose the ltinstruction-listgt in the usual way - lttestgt The same conditions used in the IF
instructions - A robot starts the loop by checking the lttestgt in
its current situation - If TRUE, the robot executes the
ltinstruction-listgt and rechecks the situation - If FALSE, the robot executes instructions that
follow the WHILE loop
36WHILE loop find the beeper
- class BeeperFinder extends Robot
- // usual constructor
- // assumes no intervening wall segments
- void findBeeper()
- while (! nextToABeeper())
- move()
-
-
37WHILE loop Clear a corner
- A robot is on a corner that may or may not have
beepers on it. The robot is to make sure that the
corner is clear of all beepers - // fill in the blanks
- void clearCorner()
-
- while ( _____________________)
- _____________________
-
-
38When to use repeating instructions
39Random Walks
- A random walk is a model built on mathematical
and physical concepts that is used to explain how
molecules move in a closed space. - Can be used as the basis for several mathematical
models that predict stock market prices - Owen Astrachan
- A Computer Science Tapestry, Chapter 7
- McGraw Hill, New York, 1997
40Random Walks
- We will use random walks as a way to further our
understanding of the use and development of
classes - We will look at a random walk in Karel
- This will coincide with moving from a
one-dimensional random walk with a single object,
to two objects walking in the same environment - Karel provides a graphical interface in our
exploration
41A Random Walk with Karel
- See RandomWalker Demo
- This application will tell us in a walk of 50
steps, how far a Robot will end up from origin
42Two-D Robots
- Suppose we wanted to track our robots in
two-dimensional space, what changes do we have to
make - To Main.java program
- To RandomWalker.java)
- Do we need another class?
43Two Robots Walk
- See CountWalker project
- Suppose we wanted to track two robots in the same
space, and see how many times they collide? - Remember, a random walk is a model ... that is
used to explain how molecules move in a closed
space, among other things
44Two Robots Walk
- This presents a special problem It is very
difficult for an object of one class to be
aware of a specific object of another class - You can pass one object of a class to another
object of a class, but it is a very difficult for
the receiving object to know that the sent object
is a specific object - The best solution is to create a superclass or
reporting class that can keep track of the
sub-classes activities in our case, we could
create a pond class that could watch our
robots, and report on the number of times they
collide - We could do this, but not at this time we will
come back to this issue later in the course
45Minilab
- Use the RandomWalker class to solve these
problems - Prompt the user for a location. Report the
number of steps the robot takes until it reaches
that position. - Given a maximum number of steps from the user,
report the number of collisions of two robots in
a two dimensional space - Right now, a 2D robot can move in only a north,
south, east, or west direction with each step.
Modify the class so that a 2D robot could move
along 8 possible compass points, including,
northeast, southeast, southwest, and northwest
(in other words, move diagonally from its
current position) - Play hide and seek with other robots using
visibility
46Simulating Board Games
- See RobotChutesLadders using GamePiece interface
class - Try Uncle Wiggly, Parcheesi