Unit 3 Introduction to Inheritance Example 1 AP





- Slides: 5

Unit 3 - Introduction to Inheritance - Example 1 AP Computer Science A – Healdsburg High School

Inheritance • In OOP a programmer can create a new class by extending an existing class Superclass (Base class) subclass extends superclass Subclass (Derived class) 2 AP Computer Science A – Healdsburg High School

A Subclass. . . 3 • 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 AP Computer Science A – Healdsburg High School

public class Pacer extends Walker { public Pacer (int x, int y, Image left. Pic, Image right. Pic) { super (x, y, left. Pic, right. Pic); } Constructor Calls Walker’s constructor using super public void turn. Around () { Foot lf = get. Left. Foot (); Foot rf = get. Right. Foot (); lf. turn (180); Calls Walker’s accessor methods rf. turn (180); lf. move. Sideways (-PIXELS_PER_INCH * 8); rf. move. Sideways (PIXELS_PER_INCH * 8); } } 4 AP Computer Science A – Healdsburg High School A new method

Example Write a subclass of Walker called Bystander should redefine (override) Walker’s first. Step, next. Step, 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 distance. Traveled method, to always return 0. 5 1) To redefine a superclass’ method in a subclass, keep its header but change the code inside the { }. 2) Define a new field which will help determine the direction of the left foot’s turn in each “step”. 3) Do not duplicate methods inherited that remain the same. AP Computer Science A – Healdsburg High School