O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Polymorphism/Abstract Methods

Problem

You want each of a number of methods in subclasses to provide its own version of a method.

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 computeArea( ), which 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 π x r

: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( ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required