// CS U213 Spring 2007 // Lecture 13: February 7, 2007 /* Goals: - More on abstract classes: adding concrete and abstract methods Introduction: Sometimes it is uselful to lift common fiels and methods of classes in a common abstract superclass. Lifting methods can be done in two ways. Methods can be added as concrete methods in the abstract class and then maybe overriden by the subclasses. Alternatively methods can be added as abstact methods in the abstract class and then implemented by the subclasses. Let's consider the following example: +------------------------------+ | IShape | +------------------------------+ | double distanceTo() | | boolean closerTo(IShape that)| | double area() | +------------------------------+ | / \ | +------------------------------+ | AShape | +------------------------------+ +------------------>| Posn location | | +------------------------------+ | | double distanceTo0() | | | boolean closerTo(IShape that)| | | double area() | | +------------------------------+ | / \ | --- | | | ---------------------------------------- | | | | | +---------------+ +--------+ +-----------+ | | Circle | | Line | | Rectangle | | +---------------+ +--------+ +-----------+ | | int radius | | int dx | | int w | | +---------------+ | int dy | | int h | | +--------+ +-----------+ | | | | | +-----------------+ +---| Posn | +-----------------+ | int x | | int y | +-----------------+ |double distTo0() | +-----------------+ Classes Circle, Line and Rectangle share common fields and methods. We lift all of them to the common abstract class AShape. Let's see how we will design and implement each one of the common methods: --------------- --distanceTo0-- --------------- This method has similar behavior for the Rectangle and Line but not for Circle. So we can implement this method as concrete method in IShape and have Circle override it with his own implementation. When Rectangle and Line refer to distanceTo0, the superclass's method is invoked. However when Circle refers to distanceTo0, the its own method is invoked.This way we skip repeating code for Rectangle and Line. //In AShape //compute this shape's distance from (0,0) double distanceTo0(){ return this.location.distTo0()} //In Circle //compute this circle's distance from (0,0) double distanceTo0(){ return this.location.distTo0()-this.radius} //No additions in Rectangle and Line ---------------- ----closerTo---- ---------------- This method has similar behavior for all shapes. So we can implement this method as concrete method in IShape. This way we skip repeating code. //In AShape //compare this shape's distance from (0,0) //with this shape's distance from (0,0) boolean closerTo(){ return this.distanceTo0()