正在加载图片...
Chapter 10: Detecting Types 作为多态性的简要回顾,我们再用程序来描述一遍上面这个例子 //: c10: Shapes. java import com. bruceeckel. simpletest. c⊥ass Shape void draw()[ System. out. println(this draw()");} class Circle extends Shape public String tostring() return Circle"i) class Square extends Shape public string tostring()i return Square"i J class Triangle extends shape i public String tostring ()( return "Triangl public class Shapes i private static Test monitor new Test()i public static void main(String[ args)I // Array of object, not shape Object[ shapelist = t new circled), () new Triangle( for(int 1=0 Shape)shapelist[i]).draw()i// Must cast monitor. expect(new String[] t le draw( 'Square. draw () Triangle. draw( 基类里有一个间接调用 tostring()来打印类的打印标识符的draw() 方法。它把this传给 System. out println(),而这个方法一看到对 象就会自动调用它的 tostring()方法,这样就能生成对象的 String表 达形式了。每个派生类都会覆写 tostring()方法(从 Object继承下来 的),这样draw()就能(多态地)打印各种对象了 man()创建了一些具体的 Shape对象并且把它们加进一个数组。这个 数组有点怪,因为它不是 Shape(尽管可以这样),而是根类 Object的 数组。这是在为第11章要讲的 collection(也称 container)作铺垫。 collection是一种工具,它只有一种用途,就是要为你保管其它对象。因 此出于通用性的考虑,这些 collection应该能持有任何东西。所以它们持 第2页共17页 www.wgqqh.com/shhgs/tij.html emailshhgsasohu.comChapter 10: Detecting Types www.wgqqh.com/shhgs/tij.html email:shhgs@sohu.com 第 2 页 共 17 页 作为多态性的简要回顾,我们再用程序来描述一遍上面这个例子: //: c10:Shapes.java import com.bruceeckel.simpletest.*; class Shape { void draw() { System.out.println(this + ".draw()"); } } class Circle extends Shape { public String toString() { return "Circle"; } } class Square extends Shape { public String toString() { return "Square"; } } class Triangle extends Shape { public String toString() { return "Triangle"; } } public class Shapes { private static Test monitor = new Test(); public static void main(String[] args) { // Array of Object, not Shape: Object[] shapeList = { new Circle(), new Square(), new Triangle() }; for(int i = 0; i < shapeList.length; i++) ((Shape)shapeList[i]).draw(); // Must cast monitor.expect(new String[] { "Circle.draw()", "Square.draw()", "Triangle.draw()" }); } } ///:~ 基类里有一个间接调用 toString( )来打印类的打印标识符的 draw( ) 方法。它把 this 传给 System.out.println( ),而这个方法一看到对 象就会自动调用它的 toString( )方法,这样就能生成对象的 String 表 达形式了。每个派生类都会覆写 toString( )方法(从 Object 继承下来 的),这样 draw( )就能(多态地)打印各种对象了。 main( )创建了一些具体的 Shape 对象并且把它们加进一个数组。这个 数组有点怪,因为它不是 Shape(尽管可以这样),而是根类 Object 的 数组。这是在为第 11 章要讲的 collection(也称 container)作铺垫。 collection 是一种工具,它只有一种用途,就是要为你保管其它对象。因 此出于通用性的考虑,这些 collection 应该能持有任何东西。所以它们持
<<向上翻页向下翻页>>
©2008-现在 cucdc.com 高等教育资讯网 版权所有