| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 418 人关注过本帖
标题:测试多态的小程序,有几个疑问
只看楼主 加入收藏
yuanxl33
Rank: 2
等 级:论坛游民
威 望:1
帖 子:60
专家分:64
注 册:2010-4-11
结帖率:85.71%
收藏
已结贴  问题点数:20 回复次数:2 
测试多态的小程序,有几个疑问
//: 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
shellingford
Rank: 9Rank: 9Rank: 9
等 级:贵宾
威 望:19
帖 子:228
专家分:1348
注 册:2010-8-9
收藏
得分:10 
程序没有错误
Circle.draw()
Triangle.draw()
Square.draw()
Circle.draw()
Square.draw()
Triangle.draw()
Circle.draw()
Triangle.draw()
Triangle.draw()



PS:检查这个java文件名是否为TestShapes.java
如果不是的确可能编译出错
2010-08-31 17:43
lampeter123
Rank: 16Rank: 16Rank: 16Rank: 16
等 级:版主
威 望:54
帖 子:2508
专家分:6424
注 册:2009-1-30
收藏
得分:10 
Thinking in JAVA书上代码没有错的,可能是你敲错了,错误提示:是第66行代码有错

你的优秀和我的人生无关!!!!
    
    我要过的,是属于我自己的生活~~~
2010-09-01 09:54
快速回复:测试多态的小程序,有几个疑问
数据加载中...
 
   



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

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