测试多态的小程序,有几个疑问
//: c07:TestShapes.java// Polymorphism in Java.
// From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
// www. See copyright notice in CopyRight.txt.
//import com.bruceeckel.simpletest.*;
import java.util.*;
class Shape {
void draw() {}
void erase() {}
}
class Circle extends Shape {
void draw() {
System.out.println("Circle.draw()");
}
void erase() {
System.out.println("Circle.erase()");
}
}
class Square extends Shape {
void draw() {
System.out.println("Square.draw()");
}
void erase() {
System.out.println("Square.erase()");
}
}
class Triangle extends Shape {
void draw() {
System.out.println("Triangle.draw()");
}
void erase() {
System.out.println("Triangle.erase()");
}
}
// A "factory" that randomly creates shapes:
class RandomShapeGenerator {
private Random rand = new Random();
public Shape next() {
switch(rand.nextInt(3)) {
default:
case 0: return new Circle();
case 1: return new Square();
case 2: return new Triangle();
}
}
}
public class TestShapes { //这行加上 public 后就编译出错
// private static Test monitor = new Test();
private static RandomShapeGenerator gen =
new RandomShapeGenerator();
public static void main(String[] args) {
Shape[] s = new Shape[9];
// Fill up the array with shapes:
for(int i = 0; i < s.length; i++)
s[i] = gen.next();
// Make polymorphic method calls:
for(int i = 0; i < s.length; i++)
s[i].draw();
/* monitor.expect(new Object[] {
new TestExpression("%% (Circle|Square|Triangle)"
+ "\\.draw\\(\\)", s.length)
}); */
}
} ///:~
运行结果,不是意料的结果
Circle.draw()
Circle.erase()
Exception in thread "main" java.lang.NoSuchMethodError: Shape.print()V
at E01_NewShapeMethod.main(E01_NewShapeMethod.java:66)