1 / 36

Code Reuse and Inheritance

Code Reuse and Inheritance. Reusing code helps you write better software, faster. Real software is based on code reuse. Inheritance lets one class inherit (reuse) behavior from another class. James Brucker Revised July 2014. Topics. Adding Bubbles to Crabgame Inheritance in Java

thanos
Download Presentation

Code Reuse and Inheritance

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Code Reuse and Inheritance Reusing code helps you write better software, faster. Real software is based on code reuse. Inheritance lets one class inherit(reuse) behavior from another class. James Brucker Revised July 2014

  2. Topics • Adding Bubbles to Crabgame • Inheritance in Java • How to use Inheritance • Code reuse • Inheritance and Constructors • Using a class that is not an Actor: SmoothMover, Mover, Vector

  3. Inheritance in Greenfoot • We've been using inheritance in our games. • One classextends another class. • What does that mean? • Why do it? superclass subclass subclass superclass subclass

  4. Actor act( ) getX( ) ...more behavior Inheritance One class is a special kind of another class. Why? We can reuse behavior. Our classes are simpler. No duplicate code. Animal canSee(Object) eat( Food ) move( ) actor behavior Crab animal behavior act() actor behavior animal behavior

  5. "Specializing" or "Extending" a Type Car start( ) stop( ) accelerate( ) Consider a basic Car... What is the behavior of a Car? An AutomaticCar is a special kind of Car with automatic transmission. AutomaticCar can do anything a Car can do. It can add extrabehavior. AutomaticCar drive( ) start( ) stop( ) accelerate( )

  6. Benefit of Extending a Type Car start( ) stop( ) accelerate( ) • Extension has many benefits: • Benefit to User: • If you can drive a basic Car, you can drive an Automatic Car. It works (almost) the same. • Benefit to Manufacturer: • You can reuse the design and behavior from Car to create AutomaticCar. Just add automatic "drive". AutomaticCar drive( ) start( ) stop( ) accelerate( )

  7. "Extension" in Greenfoot Actor act( ) getX( ) getY( ) getImage( ) getWorld( ) rotate( angle ) setLocation(x,y) setImage(image) Actor is the base class. Actor defines behavior for all kinds of actors.

  8. Actor act( ) getX( ) getY( ) getWorld( ) getImage( ) setLocation(x,y) setImage(image) Animal is a subclass of Actor. Animal can do anything an Actor can do, and ... Animal adds new behavior. Animal canSee(Object) eat( Food ) move( ) actor behavior

  9. Actor act( ) getX( ) ...more behavior Crab is a special kind of Animal. Crab can do anything an Animal can do, and anything an Actor can do, and ... adds new behavior. Animal canSee(Object) eat( Food ) move( ) actor behavior Crab animal behavior eatWithSound() actor behavior animal behavior

  10. Benefit Crab getImage( ) getWorld( ) setImage(image) setLocation(x,y) canSee(Class) eat( Food ) move( ) turn( angle ) Crab gets all the behavior from Actor and Animalfor free. We don't have to write any code! I can do all that? Freeฟรี act( ) moveWithKeybd animate()

  11. Crab can redefine behavior, too. Free act( ) getImage( ) getWorld( ) setLocation(x,y) setImage(image) Crab can change the way it behaves by defining its own "eat()" method to replace the Animal eat() method. This is called "overriding". Crabs are picky about what we eat canSee(Class) eat( Food ) move( ) turn( angle ) eat( Food )

  12. OOP "Inheritance" In OOP, inheritance means one class extends another class. Here are the names used for inheritance relationships. They mean the same thing. superclass subclass subclass

  13. What do you inherit? Object A subclass inheritsfrom its parent classes: • attributes • methods, but cannot access "private" methods Actor x y world act( ) ... In Java, Object is a superclass of all classes. Animal eat( ) move( )

  14. Question: inherit from where? From what class does Crab get each of these? x move( ) act( ) turn( 30 ) getWorld( ) setImage( image ) eat( Object ) canSee( Object )

  15. Changing inherited behavior Craboverrides the act( ) method. class Crab extends Animal { ... public void act( ) { } Crab has its own act() that overridestheact() inherited from Actor or Animal. Crab has its own act behavior

  16. Using Inheritance in Java class Animal extends Actor { public Animal( ) { super( ); } ... Write "extends" to show that one class is a subclass of another class. A class can extend only one other class. class Crab extends Animal { public Crab( ) { super( ); } ...

  17. Using Inheritance in Greenfoot Right click on a class and choose "New subclass..." Greenfoot writes the Java code for you.

  18. Constructors and Inheritance A Constructor prepares a new object for work. • Constructorinitializes a new object (attributes). • Constructor can call the superclass constructor so the parent class can initialize its attributes, too. (but you must do this first) World <<constructor>> World(width,hght,size) calls CrabWorld <<constructor>> CrabWorld( )

  19. How to invoke superclass constructor class World { public World(int width, int height, int cellsize) { // constructor } "super" must be the first statement in a constructor or not at all class CrabWorld extends World { public CrabWorld( ) { super( 500, 400, 1); setBackground( "sand.jpg" ); }

  20. How big is the world? WombatWorld: there are 8 x 6 cells, each cell is 60x60 pixels class WombatWorld extends World { public WombatWorld( ) { super( 8, 6, 60); 8 6 60 x 60

  21. How to set size of the World World constructor sets the size of the world, and number of pixels in each "cell". World <<constructor>> World(width,hght,cellsize) width=8 height=6 cellsize=60 pixels

  22. How Big is Your Screen? If your game istoo bigto see, people won'tplay! What is the resolution a computer screen? width x height (pixels) VGA = 800 x 600 XGA = 1,024 x 768 SXGA = 1,200 x 960 WXGA = ____ x ____

  23. How to use an overridden Behavior How does a Crab eat with a sound? 1. eat the same way Animal eats. 2. then play a sound (not like Animal) So. Crab "eat( )" wants to use Animal "eat( )". /** Crab eat method */ public void eat(Class food) { super.eat( food ); Greenfoot.playSound("slurp.wav"); } "super." invokes a method of the superclass.

  24. Actor Class with Special Behavior Actor SmoothMover - moves at a constant speed. You can change speed & direction. SmoothMover SmoothMover( velocity ) increaseSpeed( amount ) move( ) turn( degrees ) Vector (not an actor) - a 2D vector for velocity (speed and direction). Vector Vector(direction,length) increaseLength( amount ) scale( factor )

  25. Greenfoot Killed SmoothMover! The new Greenfoot has a SmoothMover class you can "import", but it does not move automatically! Smooth Mover We miss you

  26. Download the Classic SmoothMover Please download the classicSmoothMover.java and Vector.java (modified by Jim) from: http://se.cpe.ku.ac.th/download/ codecamp/classes Suggestion: Create a separate directory for your reusable classes, so its easy to find them.

  27. Copy these Classes to Crabgame Close the crabgame scenario. Copy SmoothMover.java and Vector.java to the crabgame directory. Then open the crabgame scenario.

  28. How to Use SmoothMover 1. Create a class that extendsSmoothMover. 2. In your class constructor, call super( Vector ) to set the direction and speed.We don't need to make a new Vector for each bubble! We can create a static Vector for all Bubbles. public class Ball extends SmoothMover { static final Vector VELOCITY = new Vector(-90, 5); public Ball( ) { super( VELOCITY ); } public void act() { move(); } Good! Easy to read.

  29. SmoothMover SmoothMover( speed ) increaseSpeed( ) move( ) turn( degrees ) Bubbles Create airbubbles that rise from the bottom of the ocean. Bubbles rise smoothly. Bubbles have different sizes. Actor Bubble

  30. Create the Bubble class Create Bubble as a subclass of SmoothMover

  31. Bubble Behavior Bubble needs to do 3 things: 1. create a translucent image 2. set its direction and speed 3. call the move() method from inside act( ). UP public void act( ) { move( ); // inherited from SmoothMover }

  32. Initialize Bubble Direction & Speed Recall how the CrabWorldset the size of world... super( 560, 460, 1); Bubble is a subclass of SmoothMover, so Bubble constructor can call the SmoothMover constructor... public class BubbleextendsSmoothMover { public Bubble( ) { // constructor super( new Vector(-90, 5) ); ...

  33. Initialize Direction and Speed Bubbles always move in the same direction (UP).We don't need to make a new Vector for each bubble! We can create a static Vector that all Bubbles share. public class Bubble extends SmoothMover { static final Vector VELOCITY = new Vector(-90, 5); public Bubble( ) { super( VELOCITY ); Easier to read and fewer objects.

  34. "Drawing" an Image GreenfootImage has methods for drawing lines, boxes, and other shapes in an image. GreenfootImageimage = new GreenfootImage(size, size); image.setColor( Color.BLUE ); image.drawOval(0, 0, size, size); (0,0) (size,size)

  35. Initializing Bubble Image We can create a circle for bubble image in constructor. public class Bubble extends SmoothMover { static final int MAXSIZE = 20; public Bubble( ) { super(VELOCITY); int size = 10; GreenfootImage image = new GreenfootImage(size, size); image.setColor( Color.BLUE ); image.drawOval(0, 0, size, size); setImage( image ); }

  36. Where are the Bubbles? • Test the Bubble class by adding some bubbles to the World interactively. • What happens when bubbles reach the top of world? Problems: Error: Cannot find symbol- Color You need to add "import java.awt.Color;" • Bubbles don't move Did you write an act( ) that calls move( )?

More Related