Recipe 9.8 PolymorphismAbstract Methods


Recipe 9.8 Polymorphism/Abstract Methods

Problem

You want each of a number of subclasses to provide its own version of one or more methods.

Solution

Make the method abstract in the parent class; this makes the compiler ensure that each subclass implements it.

Discussion

A hypothetical drawing program uses a Shape subclass for anything that is drawn. Shape has an abstract method called computeArea( ) that computes the exact area of the given shape:

public abstract class Shape {     protected int x, y;     public abstract double computeArea( ); }

A Rectangle subclass, for example, has a computeArea( ) that multiplies width times height and returns the result:

public class Rectangle extends Shape {     double width, height;     public double computeArea( ) {         return width * height;     } }

A Circle subclass returns figs/u03c0.gifr2

public class Circle extends Shape {     double radius;     public double computeArea( ) {         return Math.PI * radius * radius;     } }

This system has a very high degree of generality. In the main program, we can pass over a collection of Shape objects and here's the real beauty call computeArea( ) on any Shape subclass object without having to worry about what kind of shape it is. Java's polymorphic methods automatically call the correct computeArea( ) method in the class of which the object was originally constructed:

/** Part of a main program using Shape objects */ public class Main {     Collection allShapes;    // created in a Constructor, not shown     /** Iterate over all the Shapes, getting their areas */     public double totalAreas( ) {         Iterator it = allShapes.iterator( );         double total = 0.0;         while (it.hasNext( )) {             Shape s = (Shape)it.next( );             total += s.computeArea( );         }         return total;     } }

Polymorphism is a great boon for software maintenance: if a new subclass is added, the code in the main program does not change. Further, all the code that is specific to, say, polygon handling, is all in one place: in the source file for the Polygon class. This is a big improvement over older languages, where type fields in a structure or record were used with case or switch statements scattered all across the software. Java makes software more reliable and maintainable with the use of polymorphism.



Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net