正在加载图片...
下面这句就是在“上传”: Shape s new Circle() 这里先创建了一个 Circle对象,接着马上把它的 reference赋给了 Shape。看上去这像是一个错误(一种类型怎么能赋给另一种):但是由 于 Circle是由 Shape派生出来的, Circle就是一种 Shape,因此这 种做法非常正确。所以编译器会毫不含糊地接受这条语句,什么错都不 报 假设你调用了一个基类方法(派生类已经覆写这个方法) 可能你会认为,这次应该总调用 Shape的draw()了吧,因为毕竟这 是 Shape的 reference——编译器又怎么会知道还要做其它事情呢?但 是由于实现了后绑定(多态性),实际上它会调用 Circle. draw()。 下面的例程稍微作了一些变化: 7/: c07: Shapes. java Polymorphism in Java import com. bruceeckel simpletest* class Shape void draw()[ void erase(( class Circle extends Shape i void draw( System. out. println("Circle. draw()") oid erase i System. out. println("Circle erase()") class square extends Shape void draw([ System. out. println("Square. draw()")i void erased System. out. printin("Square erase()")i class Triangle extends shape void draw()[ 第7页共29页 www.wgqqh.com/shhgs/tij.html emailshhgsasohu.comThinking in Java 3rd Edition 第 7 页 共 29 页 www.wgqqh.com/shhgs/tij.html email:shhgs@sohu.com 下面这句就是在“上传”: Shape s = new Circle(); 这里先创建了一个 Circle 对象,接着马上把它的 reference 赋给了 Shape。看上去这像是一个错误(一种类型怎么能赋给另一种);但是由 于 Circle 是由 Shape 派生出来的,Circle 就是一种 Shape,因此这 种做法非常正确。所以编译器会毫不含糊地接受这条语句,什么错都不 报。 假设你调用了一个基类方法(派生类已经覆写这个方法): s.draw(); 可能你会认为,这次应该总调用 Shape 的 draw( )了吧,因为毕竟这 是 Shape 的 reference——编译器又怎么会知道还要做其它事情呢?但 是由于实现了后绑定(多态性),实际上它会调用 Circle.draw( )。 下面的例程稍微作了一些变化: //: c07:Shapes.java // Polymorphism in Java. 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() {
<<向上翻页向下翻页>>
©2008-现在 cucdc.com 高等教育资讯网 版权所有