所以我有这个相关的代码......
public class PokemonTrainer {
private Pokemon p = new Squirtle();
private String name;
public PokemonTrainer(String name) {
this.name = name;
}
public static void main(String[] args) {
PokemonTrainer pt = new PokemonTrainer("Ash");
try {pt.fightGary();}
catch (Charmander c) {
System.out.println("You were roasted by a Charmander.");
}
catch (Squirtle s) {
System.out.println("You were drowned by a Squirtle.");
}
catch (Bulbasaur b) {
System.out.println("You were strangled by a Bulbasaur.");
}
catch (Pokemon p) {
System.out.println("You survived!");
}
}
public void fightGary() throws Pokemon {
throw p;
}
public class Pokemon extends Exception {}
public class Bulbasaur extends Pokemon {}
public class Squirtle extends Pokemon {}
public class Charmander extends Pokemon {}
为什么会打印“你被一只松鼠淹死了”?
在我的推理中,“catch”是一个方法,当一个对象被传递到一个方法中时,该方法会根据对象的 STATIC TYPE 进行评估——在这种情况下是“Pokemon”——这在下面进行了演示简短的例子:
public class PokemonTrainer {
private Pokemon p = new Squirtle();
private String name;
public PokemonTrainer(String name) {
this.name = name;
}
public static void main(String[] args) {
PokemonTrainer pt = new PokemonTrainer("Ash");
pt.fightGary(pt.p); // ------------ Prints "Pokemon!!!"
}
public void fightGary(Pokemon p) {
System.out.println("Pokemon!!!");
}
public void fightGary(Squirtle s) {
System.out.println("Squirtle!!!");
}
}
那么这两个例子有什么不同呢?为什么第一个示例打印它的作用?
谢谢!