1 / 38

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

garran
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 subclassof 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( )

  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. GreenfootKilledSmoothMover! The new Greenfoot has a SmoothMover classyou can "import", but it does not move automatically! Smooth Mover We miss you

  26. Download the ClassicSmoothMover Please download the classicSmoothMover and Vector (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. Add these Classes to Crabgame Closethe 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 ); } 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. Add SmoothMover to your Scenario Greenfoot includes SmoothMover.java (*) 1. Edit -> Import Class2. Select SmoothMover (*) it is in the folder Greenfoot/lib/greenfoot/common

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

  32. Bubble Behavior A Bubble just moves! SmoothMover does most of the work. Bubble needs to do 3 things: 1. create an image 2. set its direction and speed 3. call the move() method from inside act( ). UP public void act( ) { move( ); // inherited from SmoothMover }

  33. Initialize Bubble Direction & Speed Recall how the CrabWorld constructor calls the World constructor (World is superclass of CrabWorld): public CrabWorld( ) { super( 560, 460, 1); } Bubble is a subclass of SmoothMover, so we can do the same thing in Bubble constructor: public class Bubble extends SmoothMover { public Bubble( ) { // constructor super( new Vector(-90, 5) ); ...

  34. 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 for all Bubbles. public class Bubble extends SmoothMover { static final Vector VELOCITY = new Vector(-90, 5); public Bubble( ) { super( VELOCITY ); Good! Easy to read and fewer objects.

  35. "Drawing" an Image GreenfootImage has methods for drawing lines, boxes, and other shapes in an image. GreenfootImage image = new GreenfootImage(size, size); image.setColor( Color.BLUE ); image.drawOval(x, y, width, height);

  36. 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 = MAXSIZE / 2; GreenfootImage image = new GreenfootImage(size, size); image.setColor( Color.BLUE ); image.drawOval(0, 0, size, size); setImage( image ); }

  37. 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( )?

  38. Exercise: Bubbles 1. Make the bubbles have random sizes. 2. Make the bubbles translucent (semi-tranparent). 3. Automatically add bubbles to the CrabWorld.

More Related