上溯造型就是upcast,子类cast成父类,很朴素的思想吗!
就好比(human)boy一样!
就好比(human)boy一样!
解决方案 »
- 怎么让按钮同时按下
- 字符串问题
- 问一个字符串解析问题。急,谢谢
- JBuilder使用说明
- 没有规例的一排排的文本,怎么取?
- 关于 CharBuffer的position() 和 Formatter的问题 jdk1.4以上
- 为什么我的程序中calendar.get(Calendar.YEAR)得到的年份总是错误的啊!
- 谁有jsp页面的语音聊天程序
- 请大家加点关注,再加点分,请帮忙:请问大家有没有把数字转成英文的class,如¥23.45 译成twenty three and fourty five cents.谢谢!
- 可以上飞信为什么不可以上手机证劵?
- helloworld 也出错,请帮忙!
- 一个打包的问题~~
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大有帮助!