class Instrument1 { public void tune() { System.out.println("tune"); } Instrument1() { System.out.println("Instrument1"); } } public class Wind1 extends Instrument1 { Wind1() { System.out.println("Wind1"); } public static void main(String[] args) { Wind1 flute = new Wind1(); flute.tune(); //这个时间不用上溯造型,因为Wind1继承了Instrument的方法 } }d:\test>java Wind1 Instrument1 Wind1 tune
class Instrument { public void play() {} static void tune(Instrument i) { // ... i.play(); } }// Wind objects are instruments // because they have the same interface: public class Wind extends Instrument { Wind() { } public static void main(String[] args) { Wind flute = new Wind(); Instrument.tune(flute); // Upcasting 这个时间就不同了,tune(Instrument)接收Instrument的参数,而实际类型是Wind,但Wind extends Instrument,所以Wind is a Instrument,可以Upcasting } }
public void play() {}
static void tune(Instrument i) {
// ...
i.play();
}
}// Wind objects are instruments
// because they have the same interface:
class Wind extends Instrument {
public static void main(String[] args) {
Wind flute = new Wind();
Instrument.tune(flute); // Upcasting
}
} 这个例子 Instrument.tune(flute); //这里是Upcasting
因为Instrument tune(Instrument i);只接收Instrument 类型,在
Instrument.tune(flute);的时间因为 flute 继承 Instrument,is a Instrument,Upcastingclass Instrument {
void tune() {}
}
class Wind extends Instrument {
public static void main(String[] args) {
Wind flute = new Wind();
flute.tune();
}
}这个就不是了 flute.tune(); 不需要吧 flute Upcasting,因为 Wind也有tune()的方法,这个只是继承
Wind flute = new Wind();
flute.tune();
修改成
Instrument flute=new Instrument();
flute.tune();
这种也可以称为“上溯造型”?另一种情况,是否“上溯造型”只能使用有参数的父类方法中,子类的对象才能调用?
{
public void tune()
{
System.out.println("tune"); }
Instrument1()
{
System.out.println("Instrument1");
}
}
public class Wind1 extends Instrument1
{
Wind1()
{
System.out.println("Wind1");
}
public static void main(String[] args)
{
Wind1 flute = new Wind1();
flute.tune(); //这个时间不用上溯造型,因为Wind1继承了Instrument的方法
}
}d:\test>java Wind1
Instrument1
Wind1
tune
{
public void play() {}
static void tune(Instrument i)
{
// ...
i.play();
}
}// Wind objects are instruments
// because they have the same interface:
public class Wind extends Instrument
{
Wind()
{
}
public static void main(String[] args)
{
Wind flute = new Wind();
Instrument.tune(flute); // Upcasting 这个时间就不同了,tune(Instrument)接收Instrument的参数,而实际类型是Wind,但Wind extends Instrument,所以Wind is a Instrument,可以Upcasting
}
}
这句话是否就是关键?在mai()方法中,本来flute是wind中的对象,执行的是flute.tune(),而使用Intstrunment.tune(flute)来调用的话,其中(flute)就是将flute.tune()转化成Intstrument.tune(flute)来调用?这里的关键是否就是(flute)?
对你理解cast大有帮助!