正在加载图片...
System. out. println(" Triangle. draw()) void erase( System. out. println("Triangleerase()") /A " factory that randomly creates shapes class RandomShapeGenerator rivate Random rand new Random ()i public Shape next() switch(rand. nextInt(3))( default urn new circle() case l: return new Square () case 2: return new Triangle ()i public class Shapes t private static Test monitor new Test( private static Random Shape Generator gen ew Random Shape Generator ( public static void main(String[] args)i Shape[] s= new Shape [9] / Fill up the array with shapes: for (int 1=0; i <slength; i++) s[i]=gen. next() / Make polymorphic method calls: for(int i =0; i<slength; i++) monitor. expect(new object[] t new TestExpression ("89 (Circle Square I Triangle) +"\\ draw\\(\)", s length 基类 Shape为继承类定义了一个共用的接口—也就是说,所有的 Shape都有draw()和 erase()这两个方法。派生类会覆写这两个方 法,以提供各自所独有的行为。 Random Shape Generator是一个“工厂”,每次调用它的next() 方法的时候,它都会随机选取一个 Shape对象,然后返回这个对象的 reference。要注意,上传就发生在 return语句,它拿到的都是 Circle, Square或是 Triangle,而它返回的都是 Shape。因此每次 调用next()的时候,你都没法知道返回值的具体类型,因为传给你的永 远是普通的 Shape reference。 man()创建了一个 Shape reference的数组,然后用 Random Shape Generator. next()把它填满。这时,你只知道它们 第8页共29页 www.wgqqh.com/shhgs/tij.html emailshhgsasohu.comChapter 7: Polymorphism 第 8 页 共 29 页 www.wgqqh.com/shhgs/tij.html email:shhgs@sohu.com 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 Shapes { 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) }); } } ///:~ 基类 Shape 为继承类定义了一个共用的接口——也就是说,所有的 Shape 都有 draw( )和 erase( )这两个方法。派生类会覆写这两个方 法,以提供各自所独有的行为。 RandomShapeGenerator 是一个“工厂”,每次调用它的 next( ) 方法的时候,它都会随机选取一个 Shape 对象,然后返回这个对象的 reference。要注意,上传就发生在 return 语句,它拿到的都是 Circle,Square 或是 Triangle,而它返回的都是 Shape。因此每次 调用 next( )的时候,你都没法知道返回值的具体类型,因为传给你的永 远是普通的 Shape reference。 main( )创建了一个 Shape reference 的数组,然后用 RandomShapeGenerator.next( )把它填满。这时,你只知道它们
<<向上翻页向下翻页>>
©2008-现在 cucdc.com 高等教育资讯网 版权所有