Topic: 关于子类上溯的问题,想不通!

  Print this page

1.关于子类上溯的问题,想不通! Copy to clipboard
Posted by: xinye0123
Posted on: 2005-03-01 21:18

//为什么输出是Wind.play()而不是Instrument.play()
class 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
}
} ///:~

2.Re:关于子类上溯的问题,想不通! [Re: xinye0123] Copy to clipboard
Posted by: dennisjl
Posted on: 2005-03-02 15:23

追踪:
1. tune(flute); //这里传入的是Wind的对象,然后执行2

2. i.play(Note.middleC); //这里的"i"指的是flute参数,也就是Wind的对象,所以打印出来的语句当然是Wind的.

public static void tune(Instrument i) {
i.play(Note.middleC);
}

上面这个方法的参数是Instrument类型,这里仅仅只是声明了一个类型,不代表它的参数就是Instrument,只要是Instrument的子类,都符合此声明,都可以作为参数传入。


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923