300 likes | 621 Views
Karel – Chapter 3 Extending the Robot Programming Language. Note: Original slides provided by www.apComputerScience.com and modified for Mr. Smith’s AP Computer Science A class. MileWalker. Compare MileWalker to the basic UrRobot: What is different? What is the same?.
E N D
Karel – Chapter 3 Extending the Robot Programming Language Note: Original slides provided bywww.apComputerScience.comand modified for Mr. Smith’s AP Computer Science A class
MileWalker Compare MileWalker to the basic UrRobot: • What is different? • What is the same? MileWalker can move 8 blocks MileWalker can move one block, turn left, pick up a beeper, put down a beeper, and turn off (just like UrRobot) In OOP terminology, it would make sense for MileWalker to inherit the capabilities of UrRobot.
Classes & Stepwise Refinement STEP 1Define a new class of robot (see next slide): When designing a new class (whether it’s a type of robot, car, bank account, etc.), the first question we are asking ourselves is “What can I steal?” !! In other words, one big benefit of OOD is the concept of code-reuse. There is no need to reinvent the wheel. (by the way, that doesn’t mean to copy your friend’s lab!! ) Also, what is different? We need to create new methods to reflect the differences.
Inserting MileWalker into the Inheritance Hierarchy UrRobot If you have an object (say, bob) of type MileWalker, what methods are available to bob? What if bob were of type UrRobot? move() turnLeft() pickBeeper() putBeeper() turnOff() MileWalker the is-Arelationship: a MileWalkeris-AUrRobot moveMile()
Inheritance superclass (or parent class) subclass import kareltherobot.*; public class MileWalker extends UrRobot { public MileWalker (int st, int av, Direction dir, int beeps) { super(st, av, dir, beeps); } public void moveMile( ) { move(); move(); move(); move(); move(); move(); move(); move(); } } constructor invokes superclass’ constructor this.move(); this.move(); this.move(); this.move(); this.move(); this.move(); this.move(); this.move(); note: no object names preceding methods (why not?) - let’s look at client code to see why
STEP 2Write application (client) to use your new object class(client is also known as a driver program). This should be a separate class from the object class. import kareltherobot.*; public class MileWalkerTester implements Directions { public static void main(String args[]) { MileWalker bob = new MileWalker(2, 1, East, 0); bob.moveMile(); // new instruction bob.move();// inherited instruction bob.turnOff(); // inherited instruction } } This client program is similar to your previous programs. Instead of constructing a UrRobot type of robot, we are constructing a MileWalker robot.
(don’t sweat this – it’s not computer science) Misc. Note • The following lines of code may be necessary and may be placed first within the main() method of the client (driver) program: • World.reset(); • World.readWorld(“MountainPeakWorld.txt"); • World.setDelay(50); • World.setVisible(true); • World.showSpeedControl(true); • Alternatively, you can place them in a static block (no need to understand what a “static block” is) within your driver class. A static block runs before the main() method runs.
Summary • You should end up with two classes: • an object class that defines the new type of robot • a client class which is used to test the new robot • The client program should test several of the methods in the new robot class: • Make the robot move a single block, a mile (8 blocks), turn left, etc. • Convention: class names begin with a Capital Letter, method names begin with a lowercase letter – if an identifier combines several words, use the “camelCase” technique. It is important to follow convention.) • We’ll now demo the whole process in eclipse and look at MileWalker and MileWalkerTester.
Now You Try! • Create a BetterRobot class • Create methods to: • turnRight(), - turns right (stays on same corner) • turnAround(), - turns backwards (stays on same corner) • moveBackward(), - moves backwards and remains in same direction • moveMile(), - moves 1 mile (8 corners) • moveDecaMile() - moves 10 miles (80 corners) • Any other methods that might be helpful?? • Create a small client program named BetterRobotTester to test the BetterRobot class • Construct the new robot • Move the robot around the screen using inherited methods or the new methods created above
How did you design BetterRobot? • Let’s get different students to write out these methods on the board: • turnRight() • turnAround() • stepBackward() • moveMile() • moveDecaMile() • What other methods did you create? • How did you test them with a client program?
Now, try something a bit more! • Design a new LetterBot robot class on paper right now that draws an E: • Create a drawE() method to draw a single letter E • This method should take advantage of any methods we created in BetterRobot (this is code reuse) • Create a client program that draws three E’s on the screen • Where does LetterBot go in the Inheritance Hierarchy? • Why is putting the same code into its one class (encapsulation) better than just leaving it in the client/driver – i.e., what do we gain?
Benefits of Encapsulation • Encapsulation is the bundling of data with the methods that act on the data. The mechanism for encapsulation in Java is the class definition. • Even though we don’t see it, the robot keeps track of data such as the street and avenue it is on, the direction it is facing, and the number of beepers it has. The methods that change this data are defined in the same class (or an inherited class) as the data. • For example, the move() method changes the street and address data stored for this robot. The turnLeft() method changes the direction data of the robot.
Benefits of Encapsulation • While creating LetterRobot, we learned that encapsulation promotes Code Reuse. By putting the code into a method, we no longer need to write that code again. In addition, from the client’s point of view, it is no longer concerned with how to draw the H – it’s the beneficiary of a concept called Abstraction(we can focus on WHAT, not HOW). • In general, if you find yourself doing a cut-and-paste, then there is a better way to do things – i.e., use procedural abstraction and abstract out the common code, putting it into a method. How did we use abstraction as we created methods in the LetterRobot class?
Improving LetterRobot Find the common code and create other methods: • drawLine() and move3() might be what you choose – you might choose others depending on how you see the problem being decomposed. How did we get access to turnRight() without recoding it? • Should the methods within LetterRobot have public or private visibility? • First explain public/private by showing methods in the BetterRobot class. • The answer to the question depends on whether we believe a client program would be calling methods like drawLine() and move3() • My opinion is that these methods (except drawE()) should be private. I’ll argue like this: the name of the class is LetterRobot and its sole purpose is to draw letters. How that object gets it done is of no concern of mine (abstraction), so I don’t need (and shouldn’t be allowed) to see the other helper/auxiliary methods. Therefore, they should be private, helper-like methods for only the LetterRobot class to us.
Stepwise Refinement • Technique for writing modules which are concise, correct, easy to read/modify/understand • Would a general contractor just start building a house – or would he/she break up the task into foundation, frame, electrical, plumbing, etc.? Makes sense, doesn’t it. Explain why from the contractor’s view – use our cs terms we’ve been learning. • Write main task first, breaking up the BIG task into smaller tasks (using methods) – then take each method one at a time and also break it up --- continue until each method is compact and singular in focus (cohesion) • Look back at what we just did – do you see this re-factoring?
Practicing Stepwise Refinement • Let’s write a class called DiamondPlanter together using stepwise refinement. It’s like Harvester except the field is diamond shaped and the robot is putting down beepers instead of picking them up. The robot should always place 4 beepers on a diagonal. Assume the robot is facing North to begin with, has 16 beepers, and is standing on the corner just below where the bottom of the diamond is to be. • What is common to another robot we have already created? • What is the main thing that it does? Name this method and it will be the one we call in the client program. • Now, break it down and identify new methods • While writing it, identify any helper methods you’d like to use. Abstract out any common code into their own unique methods (abstraction). • We’ll take each helper method in turn and repeat this stepwise-refinement process until we have cohesion (we finally get to the primitive methods).
DiamondPlanter End Situation
Debriefing DiamondPlanter • So, we wrote DiamondPlanter. More than likely we extended BetterRobot so that we could use its methods (turnRight() and maybe even a turnAround() to help us plant). • Let’s look at the Inheritance Hierarchy and see what methods we were able to take advantage of.
Improving overall object design Did we have to make any modifications to LetterRobot or BetterRobot classes to create DiamondPlanter? UrRobot BetterRobot turnRight() turnAround() LetterRobot DiamondPlanter
Now YOU try! But be efficient! Design a robot class that would be conducive to solving the following diagrammed situation (robot should climb and pick up all beepers – always 3 beepers/stair) Also, different clients need to be able to climb different numbers of stairs: starts off facing East When designing, keep in mind everything we’ve been discussing.
Why create a Class? • You want to do something that is not already defined in another class • And you also might want to use functionality already programmed in other classes. If so, use inheritance. Why reinvent the wheel? • Use Abstraction when designing your class – free your mind from the irrelevant and work on the relevant! • Ex. If I’m going to write a program to have a robot climb stairs in several buildings, I’m going to use the StairClimber class so I can call climbStair() – I can work on a bigger/better/harder problem and free my mind from the irrelevant details of taking a step and picking beepers
UrRobot BetterRobot StairClimber MileWalker Harvester DiamondPlanter Why use Inheritance? • You get stuff for free! You can be lazy (but smart)! • Use things without knowing/caring how they work! • Localize changes to one class/method (encapsulation – data and methods are in the same class)
Modifying Inherited Methods Remember MileWalker? Suppose a MileWalker can only move one mile. Every time you send it the move() command, you want it to move a mile. How would you do that? In this case you can redefine what the move() method does.
Modifying Inherited Methods import kareltherobot.*; public class MileWalker extends UrRobot { public MileWalker (int st, int av, Direction dir, int beeps) { super(st, av, dir, beeps); } public void move( ) { super.move(); super.move(); super.move(); super.move(); super.move(); super.move(); super.move(); super.move(); } } The move() method is being redefined. super.move() tells the robot to perform the move() method from the superclass (in this case UrRobot). This is called Polymorphism and we will look at this further in the next chapter.
public class MysteryBot1 extends UrRobot { /* constructor not shown */public void step1(){ move(); }public void move(){ super.move(); super.move();} } public class MysteryBot2 extends MysteryBot1 { /* constructor not shown */public void step1(){ move(); }public void move(){ super.move(); super.move();} } How many times does each robot below move? Sample Inheritance Questions MysteryBot1 joann = new MysteryBot1(10, 10 , North, 0);joann.step1(); // where is the robot now? MysteryBot2 bobby = new MysteryBot2(10, 10 , North, 0);bobby.step1(); // where is the robot now? (12, 10) facing North (14, 10) facing North
public class ABetterBot extends UrRobot { /* constructor not shown */public void step1(){ move(); }public void step2(){ turnLeft(); } } public class AnEvenBetterBot extends ABetterBot { /* constructor not shown */public void step1(){ move(); super.step1(); step2(); } public void step2(){ turnLeft(); super.step2();} } Give the state (location and Direction) of each robot below Another Inheritance Question ABetterBot ucla = new ABetterBot(10, 10 , North, 0);ucla.step1(); // where is the robot now? AnEvenBetterBot usc = new AnEvenBetterBot(10, 10 , North, 0);usc.step1(); // where is the robot now? (11, 10) facing North (12, 10) facing South
public class StepperBot extends UrRobot { /* constructor not shown */public void step1(){ move(); step2(); }public void step2(){ turnLeft();} } public class MoreStepperBot extends StepperBot { /* constructor not shown */public void step1(){ move(); super.step1(); } public void step2(){ turnLeft(); super.step2();} } Give the state (location and Direction) of each robot below A Final Inheritance Question Since step1() was called from MoreStepperBot, it looks for step2() in MoreStepperBot first StepperBot ucla = new StepperBot(10, 10 , North, 0);ucla.step1(); // where is the robot now? MoreStepperBot usc = new MoreStepperBot(10, 10 , North, 0);usc.step1(); // where is the robot now? (11, 10) facing West (12, 10) facing South
“A” is-a Letter Letter is-a Symbol Semicolon is-a PunctuationMark “@’ is-a Symbol PunctuationMark is-a Symbol LetterRobot is-a BetterRobot BetterRobot is-a UrRobot Now, split into teams and arrange the objects in the proper inheritance hierarchy Is-A relationships
Inheritance Hierarchy Symbol UrRobot PunctuationMark Letter “@” BetterBot “A” Semicolon LetterRobot