Lab 07 Inheritance and Polymorphism Inheritance Review When
Lab 07 Inheritance and Polymorphism
Inheritance - Review ØWhen objects are created, they can use methods of their superclass Robot karel = new Robot(); Athlete bob = new Athlete(); karel. move(); bob. move(); //bob can move b/c an //Athlete isa Robot
Inheritance contd. ØSubclasses inherit attributes and methods of their superclass Climber Hill. Climber Step. Climber Both Hill. Climbers and Step. Climbers can do everything Climbers can do
Overriding Methods ØSubclasses can also override methods of their superclass ØIn the Athlete class we could add a move method that makes objects move 2 spaces rather than one…. .
import edu. fcps. karel 2. Robot; import edu. fcps. karel 2. Display; public class Athlete extends Robot { public Athlete() { super(1, 1, Display. NORTH, Display. INFINITY); } public Athlete(int x, int y, int dir, int beep) { super(x, y, dir, beep); } public void turn. Around() { turn. Left(); } public void move() { move(); } 5
Overriding Methods ØNow: karel. move(); /* going to invoke Robot’s move method which moves once. */ bob. move(); /*going to invoke Athlete’s move method, which moves twice*/
Polymorphism ØHaving many forms ØLab 07 uses the following method: public static void explore(Climber x) ØAbove is the method header. ØWhat is the name of the method? explore ØHow many parameters/arguments does it accept? 1 ØWhat is the name of the argument? x ØWhat type is the argument? Climber ØIs it a formal or actual argument? formal
Polymorphism contd. public static void explore(Climber x) ØPolymorphism allows us to replace the Climber argument with any of its subclasses. Robot karel = new Robot(); Climber c = new Climber(); Step. Climber s = new Step. Climber(); explore(karel); //will NOT work explore(c); //will work explore (s); //will work
Polymorphism contd. public static void explore(Climber x) ØWe can say that the argument in the above method is polymorphic because it can refer to different types of objects at different times.
Beginning Lab 07 ØWrite the Hill. Climber and Step. Climber classes. • These will look ALMOST identical to Climber, except the code INSIDE of the climbing methods will be different. • When you tell a Step. Climber to climb. Up. Right() it means something different than when you tell a Hill. Climber to climb. Up. Right(). ØRun Lab 07 to test your methods. (Lab 07 already completed for you) ØThere is a Mountain class that is used in this lab. Open the class (Mountain. java) and use it to answer Lab 07 Exercises
- Slides: 10