靜態分派發生在編譯時期,分派根據靜態類型信息發生。方法重載就是靜態分派
public class BlackHorse implements Horse{
}
public class BlackHorse implements Horse{
}
public class WhiteHorse implements Horse {
}
public class Mozi {
public void ride(Horse h){
System.out.println("Riding a horse");
}
public void ride(WhiteHorse h){
System.out.println("Riding a white horse");
}
public void ride(BlackHorse h){
System.out.println("Riding a black horse");
}
}
public class Client {
public static void main(String[] args) {
Horse horse = new BlackHorse();
Horse horse2 = new WhiteHorse();
Mozi mozi = new Mozi();
mozi.ride(horse);
mozi.ride(horse2);
}
}
運行結果:
Riding a horse
Riding a horse