50 likes | 200 Views
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
E N D
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 • 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
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
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.