| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 418 人关注过本帖
标题:测试多态的小程序,有几个疑问
取消只看楼主 加入收藏
yuanxl33
Rank: 2
等 级:论坛游民
威 望:1
帖 子:60
专家分:64
注 册:2010-4-11
结帖率:85.71%
收藏
已结贴  问题点数:20 回复次数:0 
测试多态的小程序,有几个疑问
//: 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)
搜索更多相关主题的帖子: 多态 疑问 
2010-08-31 16:49
快速回复:测试多态的小程序,有几个疑问
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.036216 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved