【发布时间】:2015-06-23 02:14:44
【问题描述】:
请有人向我解释一下如何打印输出的最后 6 行。我知道由于静态绑定,前三行打印正确。
我不知道为什么第 5 行给出了输出,因为它是 Ipod 类型并且它没有任何歌曲方法,但它仍然打印输出。 代码如下:
package myferrari;
import mycar.*;
class IPOD
{
void PlayMusic(Music m)
{
System.out.println("Music from Ipod");
}
}
class IpodPlayer extends IPOD
{
void PlayMusic(Music m)
{
System.out.println("Music from IpodPlayer");
}
void PlayMusic(Song m)
{
System.out.println("Song from IpodPlayer");
}
}
class Music{}
class Song extends Music{}
public class Main {
public static void main(String [] args)
{
IPOD ipod = new IPOD();
IpodPlayer iplayer = new IpodPlayer();
IPOD ipl = new IpodPlayer();
Music m = new Music();
Song s = new Song();
Music sm = new Song();
iplayer.PlayMusic(m);
iplayer.PlayMusic(s);
iplayer.PlayMusic(sm); // static binding refers to the reference type
ipod.PlayMusic(m);
ipod.PlayMusic(s);
ipod.PlayMusic(sm);
ipl.PlayMusic(m);
ipl.PlayMusic(s);
ipl.PlayMusic(sm);
}
}
输出在这里:
Music from IpodPlayer
Song from IpodPlayer
Music from IpodPlayer
Music from Ipod
Music from Ipod
Music from Ipod
Music from IpodPlayer
Music from IpodPlayer
Music from IpodPlayer
【问题讨论】:
-
也许输出会很好:)
-
我已经添加了 o/p :)
-
您会说因为
Song extends Music,我们应该能够将Song传递给接受Music的方法吗? -
我认为如果我们接受这一点,我们可以将第 5 行作为输出。我仍然有疑问为什么最后一行和倒数第二行不是来自 IpodPlayer 的歌曲
-
因为 java 在编译时根据对象的类型决定使用哪种类型。注意
sm的类型是Music;playMusic(Music)将被选为要调用的方法。
标签: java oop binding polymorphism dynamic-binding