Polymorphism:
You can review the polymorphism powerpoint that we did in class for a refresher on the rules. You can also read Bergin 4.1 - 4.2.
Remember: polymorphism is the idea that one class can modify the behavior of its super class by overriding some of its methods. An object will execute the methods of the class it was constructed as, NOT what it was declared as.
Examples of this are the LongSweeper, and (hopefully) your Diamond Harvester.
Chapter 4 of the Karel book contains an ENORMOUS amount of information. We’ve talked about what’s covered in 4.1 and 4.2 - we’ll come back to the rest later. A good “Big Picture” synopsis of polymorphism (at least the part we’ve talked about so far) is covered in the first few paragraphs of section 4.10. You can stop reading when it starts talking about interfaces - we haven’t done that yet.
EXAMPLES: Consider the following class diagram:
-----------------
|class UrRobot |
-----------------
| move(); |
| turnLeft(); |
| pickBeeper(); |
| putBeeper(); |
| turnOff(); |
-----------------
^
|
-----------------
|class FooBot |
-----------------
| turnRight() |
| move2(){ |
| move(); |
| move(); |
| } |
-----------------
^
|
-----------------
|class BlahBot |
-----------------
| move(){ |
| putBeeper(); |
| super.move();|
| } |
| turnOff() |
-----------------
The following lines of code refer to the class diagram above and annotated with explanations.
UrRobot baker = new FooBot(…); //this is legal since a FooBot IS A type of UrRobot.
baker.move(); // this will compile because UrRobot’s have a move method, but it will actually run the move method defined in FooBot — which is actually just the inherited move method from UrRobot.
baker.turnRight(); // this will not compile because the compiler interprets baker as a UrRobot which does not have a turnRight method.
BlahBot franke = new FooBot(…); //this will not compile because a BlahBot is lower on the hierarchy than FooBot. This statement essentially says that FooBot is a type of BlahBot - which is not the case. (The inverse is true, however).
FooBot baker = new BlahBot(…); // legal because a BlahBot is a type of FooBot.
baker.move2(); //legal because baker, declared as a FooBot, has a method called move2(). But what will actually happen? Well, move2() makes two calls to move(). But it will run BlahBot’s move method. Since baker was actually constructed as a BlahBot it has BlahBot’s definition of move.
Leave a Reply