Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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( ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata