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( ...
Get Java Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.