1 note: original slides provided by and modified for mr. heath’s ap computer science a class

29
1 Note: Original slides provided by www.apComputerScience.com and modified for Mr. Heath’s AP Computer Science A class

Upload: lee-shields

Post on 13-Dec-2015

237 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 Note: Original slides provided by  and modified for Mr. Heath’s AP Computer Science A class

1Note: Original slides provided by www.apComputerScience.com

and modified for Mr. Heath’s AP Computer Science A class

Page 2: 1 Note: Original slides provided by  and modified for Mr. Heath’s AP Computer Science A class

2

Compare MileWalker to the basic UrRobot:

1) What is different?

2) 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.

Page 3: 1 Note: Original slides provided by  and modified for Mr. Heath’s AP Computer Science A class

3

STEP 1 Define 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.

Page 4: 1 Note: Original slides provided by  and modified for Mr. Heath’s AP Computer Science A class

4

Inserting MileWalker into the Inheritance Hierarchy

UrRobot

MileWalker

move()

moveMile()

turnLeft()

pickBeeper()

putBeeper()

turnOff()

If you have an object (say, bob) of

type MileWalker, what methods are available to bob?

What if bob were of type UrRobot?

the is-A relationship:

a MileWalker is-A UrRobot

Page 5: 1 Note: Original slides provided by  and modified for Mr. Heath’s AP Computer Science A class

5

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();

}} note: no object names preceding

methods (why not?) - let’s look at client code to see why

superclass (or parent class)

subclass

constructor

invokes superclass’ constructor

this.move(); this.move(); this.move(); this.move(); this.move(); this.move(); this.move(); this.move();

Page 6: 1 Note: Original slides provided by  and modified for Mr. Heath’s AP Computer Science A class

6

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 instructionbob.move(); // inherited instructionbob.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.

Page 7: 1 Note: Original slides provided by  and modified for Mr. Heath’s AP Computer Science A class

7

(don’t sweat this – it’s not computer science)

• These 3 method invocations may be necessary and may be placed first within the main() method of the client (driver) program:– World.reset();– 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.

Page 8: 1 Note: Original slides provided by  and modified for Mr. Heath’s AP Computer Science A class

8

• 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 BlueJ and look at MileWalker and MileWalkerTester.

Page 9: 1 Note: Original slides provided by  and modified for Mr. Heath’s AP Computer Science A class

9

• Create a BetterRobot class– Create methods to:

• turnRight(), - turns right (does not move)• turnAround(), - turns backwards (does not move)• moveBackward(), - moves backwards and remains in

same direction• moveMile(), - 1 mile = 8 corners• moveDecaMile() - 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

Page 10: 1 Note: Original slides provided by  and modified for Mr. Heath’s AP Computer Science A class

10

• Let’s get different students to write out these methods on the board:– turnRight()– turnAround() – stepBackward()– moveMile()– moveKiloMile()

• What other methods did you create?• How did you test them with a client

program?

Page 11: 1 Note: Original slides provided by  and modified for Mr. Heath’s AP Computer Science A class

11

1. Design a new LetterBot robot class on paper right now that draws an H:– Create a drawH() method to draw the H

– This method should take advantage of any methods we created in BetterRobot (this is code reuse)

– Create a client program that draws three H’s on the screen

– Where does LetterBot go in the Inheritance Hierarchy?

2. 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?

Page 12: 1 Note: Original slides provided by  and modified for Mr. Heath’s AP Computer Science A class

12

• 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.

Page 13: 1 Note: Original slides provided by  and modified for Mr. Heath’s AP Computer Science A class

13

• 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?

Page 14: 1 Note: Original slides provided by  and modified for Mr. Heath’s AP Computer Science A class

14

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 drawH()) 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.

Page 15: 1 Note: Original slides provided by  and modified for Mr. Heath’s AP Computer Science A class

15

• 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?

Page 16: 1 Note: Original slides provided by  and modified for Mr. Heath’s AP Computer Science A class

16

• 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).

Page 17: 1 Note: Original slides provided by  and modified for Mr. Heath’s AP Computer Science A class

17

End Situation

Page 18: 1 Note: Original slides provided by  and modified for Mr. Heath’s AP Computer Science A class

18

• 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.

Page 19: 1 Note: Original slides provided by  and modified for Mr. Heath’s AP Computer Science A class

19

UrRobot

BetterRobot

LetterRobot DiamondPlanter

turnRight()

turnAround()

Did we have to make any

modifications to LetterRobot or

BetterRobot classes to create

DiamondPlanter?

Page 20: 1 Note: Original slides provided by  and modified for Mr. Heath’s AP Computer Science A class

20

Now YOU try! But be efficient!

starts off

facing East

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:

When designing, keep in mind

everything we’ve been discussing.

Page 21: 1 Note: Original slides provided by  and modified for Mr. Heath’s AP Computer Science A class

21

• 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

Page 22: 1 Note: Original slides provided by  and modified for Mr. Heath’s AP Computer Science A class

22

• 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)

StairClimber MileWalker Harvester DiamondPlanter

BetterRobot

UrRobot

Page 23: 1 Note: Original slides provided by  and modified for Mr. Heath’s AP Computer Science A class

23

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.

Page 24: 1 Note: Original slides provided by  and modified for Mr. Heath’s AP Computer Science A class

24

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.

Page 25: 1 Note: Original slides provided by  and modified for Mr. Heath’s AP Computer Science A class

25

How many times does each robot below move?

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();}

}

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

Page 26: 1 Note: Original slides provided by  and modified for Mr. Heath’s AP Computer Science A class

26

Give the state (location and Direction) of each robot below

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();}

}

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

Page 27: 1 Note: Original slides provided by  and modified for Mr. Heath’s AP Computer Science A class

27

Give the state (location and Direction) of each robot below

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();}

}

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

Since step1() was called from MoreStepperBot, it looks for step2() in MoreStepperBot first

Page 28: 1 Note: Original slides provided by  and modified for Mr. Heath’s AP Computer Science A class

28

• “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

Page 29: 1 Note: Original slides provided by  and modified for Mr. Heath’s AP Computer Science A class

29

Symbol

LetterRobot

“@”

Semicolon

PunctuationMark

“A”

BetterBot

UrRobot

Letter