| 有个关于JAVA向上转型的问题 |
| [ 来源:ITWENKU 时间:2007-4-12 18:54:08 | 浏览:245人次
] |
| |
|
我有个书上的程序不明白是哪里有问题,是关于向上转型的; 有四个类文件; (1) package thinkinjava.c07;
class Instrument { public void play(){} static void tune(Instrument i){ i.play(); } } (2) package thinkinjava.c07;
public class Wind extends Instrument { public void play(Note n) { System.out.println("Wind.play() " + n); } } (3) package thinkinjava.c07;
public class Note { private String noteName;
private Note(String noteName) { this.noteName = noteName; }
public String toString() { return noteName; }
public static final Note MIDDLE_C = new Note("Middle C"), C_SHARP = new Note("C Sharp"), B_FLAT = new Note("B Flat"); } (4) package thinkinjava.c07;
public class Music { public static void tune(Instrument i){ i.play(Note.MIDDLE_C); //这里提示i.play这行出错 } public static void main(String[] agrs){ Wind flute = new Wind(); tune(flute); } }
在这里我把tune()方法里的参数改成Instrument的子类Wind就是正常的,可是这种向上转型在书上说是允许的,我不明白这是哪里错了为什么错了,所以请大家帮帮我
向上转型是允许的
Note.MIDDLE_C? 这有问题吧
Instrument 没有 play(Note.MIDDLE_C) 这个方法 只有public void play(){}
呵...谢谢大家了,我找到问题所在了,是因为Instrument类的tune和Music类的tune在调用时起冲突了.
回复www203(水户洋平): Note.MIDDLE_C? 这有问题吧
这个没有问题的,这是个枚举类;
回复frilly(秋◆水): Instrument 没有 play(Note.MIDDLE_C) 这个方法 只有public void play(){} 这个也没有错的,因为我是通过调用它的导出类Wind自动向上转型来实现的
|
|
 |
推荐文章 |
|