Karel – Chapter 4
This presentation is the property of its rightful owner.
Sponsored Links
1 / 37

Karel – Chapter 4 Polymorphism PowerPoint PPT Presentation


  • 70 Views
  • Uploaded on
  • Presentation posted in: General

Karel – Chapter 4 Polymorphism. Note: Original slides provided by www.apComputerScience.com and modified for Mr. Smith’s AP Computer Science A class. Harvester. (Ch3, pg 43). What are the options for harvesting these beepers? How many robots could we use?. Object References.

Download Presentation

Karel – Chapter 4 Polymorphism

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Karel chapter 4 polymorphism

Karel – Chapter 4

Polymorphism

Note: Original slides provided bywww.apComputerScience.comand modified for Mr. Smith’s AP Computer Science A class


Ch3 pg 43

Harvester

(Ch3, pg 43)

What are the options for harvesting these beepers?

How many robots could we use?


A k a variables

Object References

(a.k.a. variables)

  • Teams of Robots (e.g.)

    • Could have 1 robot harvest 6 rows (we’ve seen that)

    • Could have 3 robots each harvest 2 rows like this:

      Harvester botA = new Harvester(2,2,…,…);

      botA.move();

      botA.harvestTwoRows();

      Harvester botB = new Harvester(4,2,…,…);

      botB.move();

      botB.harvestTwoRows();

      Harvester botC = new Harvester(6,2,…,…);

      botC.move();

      botC.harvestTwoRows();


Karel chapter 4 polymorphism

Object References

  • Could also intersperse the operations like this:

    // same instantiations

    Harvester botA = new Harvester(2,2,…,…);

    Harvester botB = new Harvester(4,2,…,…);

    Harvester botC = new Harvester(6,2,…,…);

    botA.move();

    botB.move();

    botC.move();

    botA.harvestTwoRows();

    botB.harvestTwoRows();

    botC.harvestTwoRows();

There are 3 separate robot references in this example:

botA

botB

botC


Karel chapter 4 polymorphism

Object References

  • Could just use one reference like this:

    Harvester bot;

    bot = new Harvester(2,2,…,…);

    bot.move();

    bot.harvestTwoRows();

    bot = new Harvester(4,2,…,…);

    bot.move();

    bot.harvestTwoRows();

    bot = new Harvester(6,2,…,…);

    bot.move();

    bot.harvestTwoRows();

bot is a reference

instantiating (i.e constructing)

3 separate objects

we use assignment to assign a specific object to a reference


Karel chapter 4 polymorphism

Object References -

Common Error

  • Harvester bob;

    bob.harvestTwoRows();

  • What’s wrong with the above?

  • This causes a NullPointerException error

    • for now, an error in Java is called an exception

    • NullPointerException means the reference is not pointing to anything.

To correct the error, the object

(bob) must be instantiated

bob = new Harvester(2, 3, ..,..);


Karel chapter 4 polymorphism

Object References

  • References model what’s going on in the real world as well

    • There are lots of “Dave” references - but the particular object (person) one is referring to depends on context and whom one is, in particular, referring to at the moment

    • Well, these references are all neat and everything, but so what? Well, hold on a few more slides and you’ll see the power of using them - we’re headed toward an extremely important OO concept called Polymorphism.


Karel chapter 4 polymorphism

Polymorphism

  • Powerful example of Polymorphism:

    • pretend you are all objects - if I tell each of you to “takeABreak()”, you all will hear the same message but will act in different ways(some of you will sleep, some will walk out the door and eat something, some will try to leave school!, some will do work, etc.) - that’s polymorphism

  • sending the same message to different objects - each individual object has a particular way to interpret (implement) the message

  • so, back to code and a Java/Karel example…


Karel chapter 4 polymorphism

Overriding move()

  • remember MileWalker? (Ch3, pg 34)

    • we named its one method moveMile()

    • we could have named the method move() and then redefined what “move” means to a MileWalker. Again, we’re modeling the real world. The concept of “move” is different depending on what type of object is “moving” (think about how a dog, fish, bird, etc., “move”)

    • so, since the general concept is the same, we often use the same name (it makes coding easy/logical) - why would you want to try to remember moveMile(), moveLegs(), moveWings(), etc. - why not just one identifier for that - move()


Karel chapter 4 polymorphism

Square Robot

SquareRobot

DiagonalRightRobot

DiagonalLeftRobot

Create three separate robot classes that extend BetterRobot. Each of these robots move differently when sent the move() message.


Karel chapter 4 polymorphism

Polymorphism Example

  • let’s have 3 different types of robots

    • MileWalker

      • when move() is invoked, moves 8 miles

    • DropBeeperAndWalker

      • when move() is invoked, always drops a beeper and then moves one block forward

    • BackwardWalker (a robot tribute to Michael Jackson!)

      • when move() is invoked, moves one block backward

  • for each of these new classes, we will only have to write one method, move() - each, however, will be implemented differently, and, in addition, override the original definition of move() inherited from UrRobot --- let’s see…


As always the big picture first a k a inheritance hierarchy

MileWalker

DropBeeperAndWalker

BackwardWalker

As always, the Big Picture firsta.k.a. - Inheritance Hierarchy

UrRobot


Karel chapter 4 polymorphism

MileWalker

public class MileWalker extends UrRobot

{

// constructor same as always

public void move()

{

super.move();

super.move();

super.move();

super.move();

super.move();

super.move();

super.move();

super.move();

}

}

Method name needs to be identical to the one in the API for UrRobot in order for “overriding” to work


Karel chapter 4 polymorphism

DropBeeperAndWalker

public class DropBeeperAndWalker extends UrRobot

{

// constructor same as always

public void move()

{

putBeeper();// inherited instruction still serves its purpose

super.move();

}

}

Note: you would want to check to make sure the object always has at least one beeper for each time move() might be called


Karel chapter 4 polymorphism

BackwardWalker

  • You write it!

  • In addition to writing this class, write a sample Driver that would demonstrate using one robot each of type MileWalker, DropBeeperAndWalker, and BackwardWalker

    • We’ll pick someone and put it up in 5 minutes…


Karel chapter 4 polymorphism

Your sample Driver vs. mine

a reference can refer to any object as long as the object is of the same type or a type of one of its subclasses somewhere down the Inheritance tree!

UrRobot bot;

bot = new MileWalker(…);

bot.move(); // polymorphic move()

bot = new DropBeeperAndWalker(…);

bot.move(); // polymorphic move()

bot = new BackwardWalker(…);

bot.move(); // polymorphic move()


Karel chapter 4 polymorphism

then later…

then yet even later…

instance of MileWalker

instance of DropBeeperAndWalker

instance of BackwardWalker

Polymorphism

  • at run-time, the correct implementation is chosen depending on what specific object is being referenced at that moment in time.

bot


Karel chapter 4 polymorphism

Continue with

Square Robot

SquareRobot

DiagonalRightRobot

DiagonalLeftRobot

Create three separate robot classes that extend BetterRobot. Each of these robots move differently when sent the move() message.


Karel chapter 4 polymorphism

Polymorphism - continued

  • polymorphism is ubiquitous (everywhere) in OOP

  • there are many uses and examples of it

  • let’s now build toward another example of polymorphism

    • but first, as last time, we need some setup…


Karel chapter 4 polymorphism

Choreographers

  • one object controlling others (overseeing the movement of others)

  • we now want a MoveChoreographer class, which, when constructed, is passed 3 friends (robots)

  • the MoveChoreographer has one method called, moveFriends() which, when invoked, “moves” each friend once

  • this Choreographer model of problem solving, by the way, can been seen in the “general contractor” analogy we used in the ppt from Ch. 3 - the general contractor doesn’t really do the work, she just delegates it to other objects


Karel chapter 4 polymorphism

MoveChoreographer

public class MoveChoreographer extends UrRobot

{

private UrRobot friendA;

private UrRobot friendB;

private UrRobot friendC;

// constructor on next slide

// other methods

}

instance variables

objects not only do things (behavior), they can also remember things (state) using instance variables


Karel chapter 4 polymorphism

MoveChoreographer's constructor

public MoveChoreographer (int st,

int av, Direction dir, int numBeepers,

UrRobot botA,

UrRobot botB,

UrRobot botC )

{

super (st, av, dir, numBeepers); // must come first in method

friendA = botA;

friendB = botB;

friendC = botC;

}

instance variables being assigned


Karel chapter 4 polymorphism

MoveChoreographer's

moveFriends()

public void moveFriends()

{

friendA.move();

friendB.move();

friendC.move();

}


Karel chapter 4 polymorphism

Putting it all together

public class MoveChoreographer extends UrRobot

{

private UrRobot friendA;

private UrRobot friendB;

private UrRobot friendC;

public MoveChoreographer (int st, int av, Direction dir, int numBeepers,

UrRobot botA, UrRobot botB, UrRobot botC )

{

super (st, av, dir, numBeepers); // must come first in method

friendA = botA;

friendB = botB;

friendC = botC;

}

public void moveFriends()

{

friendA.move();

friendB.move();

friendC.move();

}

}


Karel chapter 4 polymorphism

Sample Client code using a

MoveChoreographer

Can you now give some sample client code that uses a MoveChoreographer object? Pass a MileWalker, DropBeeperAnd Walker and a BackardWalker to the MoveChoreographer object (do so now for 5 minutes…)

an example:

UrRobot bot1 = new MileWalker(2, 4, North, 0) ;

UrRobot bot2 = new DropBeeperAndWalker(2, 5, North, infinity);

UrRobot bot3 = new BackwardWalker(2, 6, North, 0);

MoveChoreographer chor;

chor = new MoveChoreographer(1, 1, North, 0, bot1, bot2, bot3);

chor.moveFriends();

draw a picture and show the before and after


Karel chapter 4 polymorphism

Examining the constructor’s

reference types

The statement from the previous slide,

chor = new MoveChoreographer(1, 1, North, 0, bot1, bot2, bot3);

is kind of neat. When someone constructs a MoveChoreographer, he can pass any 3 robots in any order as long as each one is-A UrRobot (it extends from a UrRobot).

The MoveChoreographer only wants to be guaranteed that it can perform a move() on any object passed to it - since there is a move() in UrRobot, it chose to make its parameters of type UrRobot, guaranteeing (to itself and the compiler) that it will be able to call move() at run-time. The term that describes which particular move() will be called at run-time is ____________.

Polymorphism


Karel chapter 4 polymorphism

Gardener

Initial Situation

End Situation

gardenerWorld.txt

Create a Gardener robot that will use GardenerHelper robots to help plant a garden. The Gardener class will have a constructor method similar to the MoveChoreographer robot that we created in class. Gardener’s specialty is to supervise 3 other GardenerHelper robots to plant beepers. You should program the GardenerHelper class to plant beepers around the plus-shaped wall. The GardenerHelper is a BetterRobot and the Gardener robot is a GardenerHelper. The Gardener robot should be programmed to use itself and the 3 other robots that are passed to it to plant each corner. The client program should pass the helper robots to the Gardener robot in the correct street/avenue that they should start on and facing in the correct direction.


Karel chapter 4 polymorphism

Abstract classes

  • Sometimes we want to do several tasks, but the tasks are very similar. How can we build the classes to take advantage of the common parts of the task and yet distinguish the specific differences? Another way to say that is, how can we design the inheritance tree so that we don’t duplicate common code used among sub-classes, yet allow sub-classes to have some specific differences?

  • The answer is: use an abstract class…


Karel chapter 4 polymorphism

Example of the need

for an abstract class

Here is a task for a team of robots. We want to lay down beepers in a 5-by-4 field. The odd-numbered rows have 2 beepers per street corner, the even have 3.


Karel chapter 4 polymorphism

UrRobot

discuss problems with design

TwoRowLayer

ThreeRowLayer

layBeepers()

layBeepers()

putBeepers()

putBeepers()

abstract class example

Here is how we’d organize that with what we currently know:


Karel chapter 4 polymorphism

BeeperLayers

On the previous slide, we saw that layBeepers() would have the exact same implementation for both types of beeper layers - namely:

public void layBeepers()

{

move();

putBeepers();

move();

putBeepers();

move();

putBeepers();

move();

putBeepers();

move();

}

discuss why code duplication (a.k.a., copy/paste) and lack of localization are poor/costly design patterns


Karel chapter 4 polymorphism

BeeperLayers

At the same time, we saw that putBeepers() would have a different implementation in each of the subclasses (one puts 2, the other puts 3). So here is the new design pattern:

We’ll extract out an abstract concept of what a general beeper layer would look like and put that into a class (in this case, an abstract class). Methods in the abstract class that have the exact same implementation regardless of the subclass will be implemented in the abstract class.Methods that would have different implementations in the subclasses will not be implemented in the abstract class, forcing each subclass to give its own unique implementation…


Karel chapter 4 polymorphism

UrRobot

BeeperLayer

public void layBeepers() { … }

public abstract void putBeepers();

TwoRowLayer

ThreeRowLayer

public void putBeepers() { … }

public void putBeepers() { … }

Inheritance Hierarchy


Karel chapter 4 polymorphism

Putting it all together

public abstract class BeeperLayer extends UrRobot

{

public BeeperLayer(int street, int avenue, Direction direction, int beepers)

{

super(street, avenue, direction, beepers);

}

// The following abstract method will be used by TwoRowLayer and ThreeRowLayer

public abstract void putBeepers();

public void layBeepers()

{

move();

putBeepers();

move();

putBeepers();

move();

putBeepers();

move();

putBeepers();

move();

}

}

public class TwoRowLayer extends BeeperLayer

{

public TwoRowLayer( int st, int av, Direction dir, int beeps)

{

super(st, av, dir, beeps);

}

public void putBeepers()

{

putBeeper();

putBeeper();

}

}


Karel chapter 4 polymorphism

Terminology & Concepts

public class BeeperLayerTester implements Directions

{

public static void main(String[] args)

{

BeeperLayer lisa;

lisa = new TwoRowLayer(1, 3 ,East, infinity);

lisa.layBeepers();

lisa = new ThreeRowLayer(2, 3, East, infinity);

lisa.layBeepers();

lisa = new TwoRowLayer(3, 3, East, infinity);

lisa.layBeepers();

lisa = new ThreeRowLayer(4, 3, East, infinity);

lisa.layBeepers();

lisa = new TwoRowLayer(5, 3, East, infinity);

lisa.layBeepers();

}

}

making references to the code, the inheritance tree, or whatever else we just discussed in the BeeperLayer problem, pick one of these terms and demonstrate that you know what it means

abstraction, abstract class, abstract method, polymorphism


Karel chapter 4 polymorphism

Terminology

  • Abstraction - Mechanism and practice to reduce and factor out details so that one can focus on a few concepts at a time (i.e. abstracting common code and putting it into a method)

  • Abstract class – Special class used to provide common code used among sub-classes, yet allow sub-classes to have some specific differences. It is not possible to create an instance of an abstract class (it must be extended and then that class can be instantiated). An abstract class that only contains abstract methods is an interface (we’ll learn about that later).

  • Abstract method – Method in an abstract class that must be redefined in a class that extends the abstract class.

  • Polymorphism – Objects in different classes can behave differently when sent the same message. In practical terms, polymorphism means that if class B inherits from class A, it doesn’t have to inherit everything about class A; it can do some of the things that class A does differently.


Karel chapter 4 polymorphism

Terminology (cont.)

  • Initialize – Set the value of a variable to a specific value For example: karel = new UrRobot(1, 2, North, 0);

  • Assignment – Used to change the object to which an reference points. Use the equal sign (=) to denote assignment.

  • Reference (or Variable) – name used to identify a field (i.e. the robot name “karel” is a reference or variable).

  • Instance Variable (or Field) – The things that an object remembers. These are the variables defined in the object class.

  • null – Special value to indicate that the reference to the variable does not refer to anything at all (i.e. UrRobot karel = null).

  • Parameter – Information sent to a method. When we instantiate a new robot object, we are passing 4 different parameters which are used by the constructor method. Parameters can be of any type.


  • Login