80 likes | 313 Views
Karel J. Robot: A Gentle Introduction to the Art of Object-Oriented Programming in Java by Joseph Bergin et al. Chapter 3 Extending the Robot Programming Language.
E N D
Karel J. Robot:A Gentle Introduction to the Art of Object-Oriented Programming in Javaby Joseph Bergin et al Chapter 3 Extending the Robot Programming Language Slides modified from work by Dave Wittry of Troy High School in Fullerton, CAwith supporting material from:Object Oriented Programming: a one-hour introduction to OOPby Tom West, Holt Software andObject-Oriented Programming in Java using Karelby Sandy Graham, University of Waterloo Chapter 3
Making and Using New Classes STEP 1 Define a new class of robot (see next slide) Chapter 3
subclass superclass (parent class) constructor import kareltherobot.*; public class MileWalker extends ur_Robot { public MileWalker (int st, int av, Directions.Direction dir, int beeps) { super(st, av, dir, beeps); } public void moveMile( ) { move(); move(); move(); move(); move(); move(); move(); move(); } } super = a ur_Robot Note: no object names preceding method calls, but could use this.move(); Chapter 3
STEP 2Write a program that uses the new class: import kareltherobot.*; public class MileWalkerTest 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(); } } Chapter 3
Note before Step 3 These 3 method calls are necessary to see Karel and his world. Place them in the “main” method: • World.readWorld("first.wld") • World.setDelay(50); • World.setVisible(true); Chapter 3
STEP 3 • Put each class in its own files making sure that the file name matches the class name exactly; • Remember: class names begin with a capital letter and method/function names begin with a lower case letter; • Save the classes in the same project. Chapter 3
Key Words Subclasses (child classes) inherit the capabilities (methods) of their super classes (parent classes) Subclasses extend their parent classes e.g., public class fastRobot extends ur_Robot {...} Methods of a parent class may be overridden by methods of their subclasses e.g., fastRobot could have a move method which replaces the move method, inherited from ur_Robot, for all fastRobots Chapter 3
Stepwise Refinement • A method for writing programs/systems which are concise, correct, easy to read/modify/understand • Write main program first • break up the BIG task into smaller tasks (using methods) • Write each method one at a time • break each up into smaller tasks using more methods • Repeat until each method is compact and singular in focus (cohesion) Chapter 3