《Thing in java》上塑造型的笔记
来源:互联网 发布:在淘宝上搜春药怎么搜 编辑:程序博客网 时间:2024/06/01 09:35
//: Music.java// Inheritance & upcastingclass Note { private int value; private Note(int val) { value = val; } public static final Note middleC = new Note(0), cSharp = new Note(1), cFlat = new Note(2);} // Etc.class Instrument { public void play(Note n) { System.out.println("Instrument.play()"); }}// Wind objects are instruments// because they have the same interface:class Wind extends Instrument { // Redefine interface method: public void play(Note n) { System.out.println("Wind.play()"); }}public class Music { public static void tune(Instrument i) { // ... i.play(Note.middleC); } public static void main(String[] args) { Wind flute = new Wind(); tune(flute); // Upcasting }} ///:~
其中,方法 Music.tune()接收一个Instrument 句柄,同时也能接收从Instrument 衍生出来的所有东西。当一个Wind 句柄传递给 tune()的时候,就会出现这种情况。此时没有造型的必要。这样做是可以接受的;
Instrument 里的接口必须存在于 Wind 中,因为Wind 是从Instrument 里继承得到的。从 Wind 向Instrument的上溯造型可能“缩小”那个接口,但不可能把它变得比 Instrument 的完整接口还要小。
阅读全文
0 0
- 《Thing in java》上塑造型的笔记
- Thing-in-java
- Thing-in-Java(P57)
- Thing-in-Java(P58)
- Thing-in-Java(P61)
- 《Thing in java》多态
- 《Thing in Java》对final关键字的介绍之数据
- <java编程思想>(thing in java) 阅读笔记(第一章至第六章)
- <java编程思想>(thing in java) 阅读笔记(第七章至第十章)
- <java编程思想>(thing in java) 阅读笔记(第十一章至第十二章)
- <java编程思想>(thing in java) 阅读笔记(第十三章至第十五章)
- <java编程思想>(thing in java) 阅读笔记(第十六章至第二十一章)
- java类的加载顺序,父类和子类初始化的顺序和重写所遇到的上塑造型
- 《THING IN JAVA》 13章字符串-读书笔记
- 《THING IN JAVA》 9章接口-读书笔记
- 《THING IN JAVA》 7章复用类-读书笔记
- 《THING IN JAVA》 8章多态-读书笔记
- 《Thing In Java》 笔记1(3,4,5,6章)
- SFP-10G-SR vs. SFP-10G-SR-S
- Cannot evaluate tensor using `eval()`: No default session is registered. Use `with sess.as_default()
- [jQuery] 添加读取csv文件的扩展
- windows系统 安装MongoDB 32位
- java设计模式之代理模式
- 《Thing in java》上塑造型的笔记
- Python 重定向 响应头
- X64与X86各个类型的长度
- SpringBoot 项目如何在tomcat容器中运行
- tar命令的详细解释
- 微信红包订单存储架构变迁的最佳实践
- Spread Studio跨平台表格控件集发布V11版本,速度更快、内存更省
- Kotlin 开发
- YYCache学习