Download presentation
Presentation is loading. Please wait.
Published byStanisław Łukasik Modified over 5 years ago
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 extends Walker
{ 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.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.