Download presentation
Presentation is loading. Please wait.
1
Karel J Robot Chapter 4 B
2
Abstract classes Sometimes we want to do several tasks, but the tasks are very similar. How can we build the classes to take advantage of the common parts of the task and yet distinguish the specific differences? Another way to say that is, how can we design the inheritance tree so that we don’t duplicate common code used among sub-classes, yet allow sub-classes to have some specific differences? The answer = use an abstract class… Chapter 4 B
3
contrived/simple task to demo the need for an abstract class
run demo Here is a task for a team of robots. We want to lay down beepers in a 5-by-4 field. The odd-numbered rows have 2 beepers per corner, the even have 3. Here is how we’d organize that with what we currently know: UrRobot TwoRowLayer ThreeRowLayer layBeepers() putBeepers() discuss problems with design Chapter 4 B
4
BeeperLayers On the previous slide, we saw that layBeepers() would have the exact same implementation for both types of beeper layers - namely: { move(); putBeepers(); move(); } discuss why code duplication (a.k.a., copy/paste) and lack of localization are poor/costly design patterns Chapter 4 B
5
BeeperLayers At the same time, we saw that putBeepers() would have a different implementation in each of the subclasses (one puts 2, the other puts 3). So here is the new design pattern: We’ll extract out an abstract concept of what a general beeper layer would look like and put that into a class(in this case, an abstract class). Methods in the abstract class that would have the exact same implementation regardless of the subclass will be implemented in the abstract class - methods that would have different implementations in the subclasses will not be implemented in the abstract class, forcing each subclass to give its own unique implementation… Chapter 4 B
6
Inheritance Hierarchy
UrRobot BeeperLayer public void layBeepers() { … } public abstract void putBeepers(); TwoRowLayer public void putBeepers() { … } ThreeRowLayer public void putBeepers() { … } Chapter 4 B
7
Terminology & Concepts
BeeperLayer lisa = null; lisa = new TwoRowLayer(1, 3 ,East, infinity); lisa.layBeepers(); lisa = new ThreeRowLayer(2, 3, East, infinity); lisa.layBeepers(); lisa = new TwoRowLayer(3, 3, East, infinity); lisa.layBeepers(); lisa = new ThreeRowLayer(4, 3, East, infinity); lisa.layBeepers(); lisa = new TwoRowLayer(5, 3, East, infinity); lisa.layBeepers(); making references to the code, the inheritance tree, or whatever else we just discussed in the BeeperLayer problem, pick one of these terms and demonstrate that you know what it means abstraction, abstract class, abstract method, polymorphism Chapter 4 B
8
Chapter 4 B
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.