1 / 5

Unit 3 - Introduction to Inheritance - Example

Unit 3 - Introduction to Inheritance - Example. Inheritance. In OOP a programmer can create a new class by extending an existing class. Superclass (Base class). subclass extends superclass. Subclass (Derived class). A Subclass. inherits fields and methods of its superclass

maine
Télécharger la présentation

Unit 3 - Introduction to Inheritance - Example

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. Unit 3- Introduction to Inheritance- Example

  2. Inheritance • In OOP a programmer can create a new class by extending an existing class Superclass (Base class) subclass extends superclass Subclass (Derived class)

  3. A Subclass... • inherits fields and methods of its superclass • can add new fields and methods • can redefine (override) a method of the superclass • must provide its own constructors, but calls superclass’s constructors • does not have direct access to its superclass’s private fields

  4. public class Pacer extendsWalker { public Pacer (int x, int y, Image leftPic, Image rightPic) { super (x, y, leftPic, rightPic); } public void turnAround () { Foot lf = getLeftFoot (); Foot rf = getRightFoot (); lf.turn (180); rf.turn (180); lf.moveSideways (-PIXELS_PER_INCH * 8); rf.moveSideways (PIXELS_PER_INCH * 8); } } Constructor Calls Walker’s constructor using super A new method Calls Walker’s accessor methods

  5. Example • Write a subclass of Walker called Bystander. Bystander should redefine (override) Walker’s firstStep, nextStep, and stop methods in such a way that Bystander alternates turning it’s left foot by 45 degrees left and right on subsequent steps but never moves the right foot. Bystander should also redefine the distanceTraveled method, to always return 0. • To redefine a superclass’ method in a subclass, keep its header but change the code inside the { }. • Define a new field which will help determine the direction of the left foot’s turn in each “step”. • Do not duplicate methods inherited that remain the same.

More Related