1 Ch. 4.1 - 4.3 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.

Slides:



Advertisements
Similar presentations
OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
Advertisements

1 Note: Original slides provided by and modified for Mr. Smith’s AP Computer Science A classwww.apComputerScience.com.
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
1 Ch. 3 Ch.3 Classes & Stepwise Refinement STEP 1 Define a new class of robot (see next slide) When designing a new class (whether that’s robots, cars,
Georgia Institute of Technology Workshop for CS-AP Teachers Chapter 3 Advanced Object-Oriented Concepts.
1 Inheritance in Java Behind the scenes: new Objects from old.
ITEC200 – Week03 Inheritance and Class Hierarchies.
CS 106 Introduction to Computer Science I 11 / 09 / 2007 Instructor: Michael Eckmann.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
CS 106 Introduction to Computer Science I 11 / 20 / 2006 Instructor: Michael Eckmann.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
CS 106 Introduction to Computer Science I 03 / 21 / 2008 Instructor: Michael Eckmann.
Polymorphism Are there different ways to solve the Harvester problem? – Robot teams – instead of one robot to solve a problem, let’s get a team of robots.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
25-Jun-15 Starting Classes and Methods. Objects have behaviors In old style programming, you had: data, which was completely passive functions, which.
CS 106 Introduction to Computer Science I 03 / 30 / 2007 Instructor: Michael Eckmann.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
Abstraction: Polymorphism, pt. 1 Abstracting Objects.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
Extending the Robot Programming Language In the Robot world 1 mile = 8 blocks Suppose we want a robot to run a marathon (26+ miles)? Does our program have.
Lecture 7 Polymorphism. Review: Constructors ●Parenthesis after constructor, not in class declaration ●The constructor makes the SamBot – do not “ new.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
Karel J Robot An introduction to BlueJ and Object- Oriented Programming.
1 Ch. 7 Recursion similar to iteration in that you repeatedly do a little bit of the task and then “loop” again and work on a smaller piece - eventually.
CS 350 – Software Design The Object Paradigm – Chapter 1 If you were tasked to write code to access a description of shapes that were stored in a database.
1 Note: Original slides provided by and modified for Mr. Smith’s AP Computer Science A classwww.apComputerScience.com.
Class Inheritance UNC-CHAPEL HILL COMP 401 BRIAN CRISTANTE 5 FEBRUARY 2015.
CMSC 202 Generics. Nov Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
1 Note: Original slides provided by and modified for Mr. Smith’s AP Computer Science A classwww.apComputerScience.com Day 3.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
CS 106 Introduction to Computer Science I 04 / 23 / 2010 Instructor: Michael Eckmann.
Karel J. Robot Tool for learning OOP (Lecture covers Ch. 1 and 2)
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
1 Note: Original slides provided by and modified for Mr. Smith’s AP Computer Science A classwww.apComputerScience.com If you.
Programming in Java CSCI-2220 Object Oriented Programming.
Object Oriented Software Development
1 Note: Original slides provided by and modified for Mr. Heath’s AP Computer Science A classwww.apComputerScience.com.
1 CS161 Introduction to Computer Science Topic #9.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
1 Note: Original slides provided by and modified for Mr. Smith’s AP Computer Science A classwww.apComputerScience.com Day 4.
CS 106 Introduction to Computer Science I 04 / 18 / 2008 Instructor: Michael Eckmann.
1 Note: Original slides provided by and modified for Mr. Smith ’ s AP Computer Science A classwww.apComputerScience.com.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Ch. 2 1 Karel – Primitive Instructions Basic tools with which all problems are solved (analogies: carpentry, geometry) –move() –turnLeft() –putBeeper()
Inheritance and Polymorphism. Superclass and Subclass Inheritance defines a relationship between objects that share characteristics. It is a mechanism.
CS2102: Lecture on Abstract Classes and Inheritance Kathi Fisler.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
1 Ch. 3 Ch.3 Classes & Stepwise Refinement STEP 1 Define a new class of robot (see next slide) When designing a new class (whether that’s robots, cars,
Overview of C++ Polymorphism
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
OOP Basics Classes & Methods (c) IDMS/SQL News
1 Note: Original slides provided by and modified for Mr. Smith’s AP Computer Science A classwww.apComputerScience.com.
Lecture 10 – Polymorphism Nancy Harris with additional slides Professor Adams from Lewis & Bernstein.
Inheritance a subclass extends the functionality of a superclass a subclass inherits all the functionality of a superclass don't reinvent the wheel – "stand.
Inheritance and Polymorphism
Ch.3 Classes & Stepwise Refinement
Ch.3 Classes STEP 1 Define a new class of robot (see next slide)
Karel J Robot Chapter 4 B.
Polymorphism Simple but profound!.
Ch.3 Classes & Stepwise Refinement
Object References a.k.a. variables
Ch.3 Classes & Stepwise Refinement
Ch.3 Classes & Stepwise Refinement
Presentation transcript:

1 Ch 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,…,…); Harvester botB = new Harvester(4,2,…,…); Harvester botC = new Harvester(6,2,…,…); botA.move();botA.harvestTwoRows(); botB.move();botB.harvestTwoRows(); botC.move();botC.harvestTwoRows();

2 Ch Object References Could also intersperse the operations like this: // same instantiations botA.move(); botB.move(); botC.move(); botA.harvestTwoRows(); botB.harvestTwoRows(); botC.harvestTwoRows();

3 Ch 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(); a reference instantiating 3 objects we use assignment to assign a specific object to a reference

4 Ch Object References - Common Error Harvester bob; bob.harvestTwoRows(); What’s wrong with the above? NullPointerException –for now, an error in Java is called an exception –do you think this error happens at run-time or compile-time? why? Binky Pointer Video (instructors: you can find it and other neat cs videos/materials at - you’ll want to download ahead of time, as it is huge)Binky Pointer Video

5 Ch 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.

6 Ch Polymorphism Powerful example: –you are all objects - if I tell all 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…

7 Ch Overriding move() remember MileWalker? –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()

8 Ch Example let’s have 3 different types of bots –MileWalker when move() is invoked, moves 1 mile –DropBeeperAndWalker when move() is invoked, always drops a beeper and then moves one block forward –BackwardWalker (sort of the Michael Jackson of robots!) 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 ur_Robot --- let’s see…

9 Ch As always, the Big Picture first a.k.a. - Inheritance Hierarchy ur_Robot MileWalker BackwardWalker DropBeeperAndWalker

10 Ch MileWalker public class MileWalker extends ur_Robot { // constructor same as always public void move() { super.move(); } heading needs to be identical to the one in the API for ur_Robot in order for “overriding” to work

11 Ch DropBeeperAndWalker public class DropBeeperAndWalker extends ur_Robot { // constructor same as always public void move() { putBeeper(); // inherited instruction still serves its purpose super.move(); } class invariant: object always has at least one beeper for each time move() might be called (AB topic)

12 Ch 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…

13 Ch Your sample Driver vs. mine ur_Robot bot; bot = new MileWalker(…); bot.move(); // polymorphic move() bot = new DropBeeperAndWalker(…); bot.move();// polymorphic move() bot = new BackwardWalker(…); bot.move(); // polymorphic move() 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!

14 Ch Polymorphism at run-time, the correct implementation is chosen depending on what specific object is being referenced at that moment in time. bot instance of MileWalker then yet even later… instance of BackwardWalker then later… instance of DropBeeperAndWalker

15 Ch Polymorphism - cont’d polymorphism is ubiquitous in OO 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…

16 Ch Choreographers one object controlling 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 another object(s)

17 Ch MoveChoreographer public class MoveChoreographer extends ur_Robot { // constructor on next slide // other methods private ur_Robot delegateA; private ur_Robot delegateB; private ur_Robot delegateC; } instance variables objects can not only do(behavior) things, they can also remember(state) things

18 Ch MoveChoreographer’s constructor public MoveChoreographer ( int st, int av, Direction dir, int numBeepers, ur_Robot botA, ur_Robot botB, ur_Robot botC ) { super (st, av, dir, numBeepers); // must come first in method delegateA = botA; delegateB = botB; delegateC = botC; } instance variables being assigned

19 Ch MoveChoreographer’s moveFriends() public void moveFriends() { delegateA.move(); delegateB.move(); delegateC.move(); }

20 Ch Sample Client code using a MoveChoreographer can you now give some sample client code that uses a MoveChoreographer object? (do so now for 5 minutes…) an example: ur_Robot bot1 = new MileWalker(2, 4, North, 0) ; ur_Robot bot2 = new DropBeeperAndWalker(2, 5, North, infinity); ur_Robot bot3 = new BetterTurner(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

21 Ch 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 ur_Robot or extends from a ur_Robot. 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 ur_Robot, it chose to make its parameters of type ur_Robot, 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 ____________?

22 Ch 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 = use an abstract class…

23 Ch 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 corner, the even have 3. Here is how we’d organize that with what we currently know: contrived/simple task to demo the need for an abstract class ur_Robot TwoRowLayerThreeRowLayer layBeepers() putBeepers() discuss problems with design run demo

24 Ch BeeperLayers On the previous slide, we saw that layBeepers() would have the exact same implementation for both types of beeper layers - namely: { move();putBeepers(); move(); } discuss why code duplication (a.k.a., copy/paste) and lack of localization are poor/costly design patterns

25 Ch 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 would 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…

26 Ch Inheritance Hierarchy TwoRowLayer public void putBeepers() { … } ur_Robot BeeperLayer public void layBeepers() { … } public abstract void putBeepers(); ThreeRowLayer public void putBeepers() { … }

27 Ch Terminology & Concepts BeeperLayer lisa = null; 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(); abstraction, abstract class, abstract method, polymorphism 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