`

Polymorphism classic example

    博客分类:
  • Java
 
阅读更多

The classic example in OOP is the “shape” example. This is commonly used because it is easy to visualize, but unfortunately it can confuse novice programmers into thinking that OOP is just for graphics programming, which is of course not the case.

 

The shape example has a base class called Shape and various derived types: Circle, Square, Triangle, etc. The reason the example works so well is that it’s easy to say “a circle is a type of shape” and be understood. The inheritance diagram shows the relationships:


The upcast could occur in a statement as simple as:
Shape s = new Circle();


Here, a Circle object is created, and the resulting reference is immediately assigned to a Shape, which would seem to be an error (assigning one type to another); and yet it’s fine because a Circle is a Shape by inheritance. So the compiler agrees with the statement and doesn’t issue an error message.

 

Suppose you call one of the base-class methods (that have been overridden in the derived classes):
s.draw();

 

Again, you might expect that Shape’s draw( ) is called because this is, after all, a Shape reference—so how could the compiler know to do anything else? And yet the proper Circle.draw( ) is called because of late binding (polymorphism).
The following example puts it a slightly different way. First, let’s create a reusable library of Shape types:

Shape.java

package org.fool.polymorphism;

public class Shape {
	public void draw() {
	}

	public void erase() {
	}
}

 Circle.java

package org.fool.polymorphism;

public class Circle extends Shape {

	@Override
	public void draw() {
		System.out.println("Circle.draw()");
	}

	@Override
	public void erase() {
		System.out.println("Circle.erase()");
	}

}

 Square.java

package org.fool.polymorphism;

public class Square extends Shape {

	@Override
	public void draw() {
		System.out.println("Square.draw()");
	}

	@Override
	public void erase() {
		System.out.println("Square.erase()");
	}

}

 Triangle.java

package org.fool.polymorphism;

public class Triangle extends Shape {

	@Override
	public void draw() {
		System.out.println("Triangle.draw()");
	}

	@Override
	public void erase() {
		System.out.println("Triangle.erase()");
	}

}

 PolymorphismTest.java

package org.fool.polymorphism;

import java.util.Random;

public class PolymorphismTest {

	public static class RandomShapeGenerator {
		private static Random rand = new Random(47);

		public static Shape next() {
			switch (rand.nextInt(3)) {
			default:
			case 0:
				return new Circle();
			case 1:
				return new Square();
			case 2:
				return new Triangle();
			}
		}
	}

	public static void main(String[] args) {
		Shape[] shapes = new Shape[9];

		// Fill up the array with shapes:
		for (int i = 0; i < shapes.length; i++) {
			shapes[i] = RandomShapeGenerator.next();
		}

		// Make polymorphic method calls:
		for (Shape s : shapes) {
			s.draw();
		}
	}
}

 

The base class Shape establishes the common interface to anything inherited from Shape—that is, all shapes can be drawn and erased. The derived classes override these definitions to provide unique behavior for each specific type of shape.

RandomShapeGenerator is a kind of “factory” that produces a reference to a randomly-selected Shape object each time you call its next( ) method. Note that the upcasting happens in the return statements, each of which takes a reference to a Circle, Square, or Triangle and sends it out of next( ) as the return type, Shape. So whenever you call next( ), you never get a chance to see what specific type it is, since you always get back a plain Shape reference.

main( ) contains an array of Shape references filled through calls to RandomShapeGenerator.next( ). At this point you know you have Shapes, but you don’t know anything more specific than that (and neither does the compiler). However, when you step through this array and call draw( ) for each one, the correct type-specific behavior magically occurs, as you can see from the output when you run the program.

The point of creating the shapes randomly is to drive home the understanding that the compiler can have no special knowledge that allows it to make the correct calls at compile time. All the calls to draw( ) must be made through dynamic binding.

 

  • 大小: 8 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics