请查看此问题,以便更好地理解上传和下传:
我也做了一个看待上传行为的例子:
abstract class Animal
{
public void saySomething()
{
System.out.println("Some Animal sound");
}
public abstract void getTheBall();
}
class Horse extends Animal
{
public void saySomething()
{
System.out.println("Neigh Neigh");
}
public void getTheBall()
{
System.out.println("I won't,Try a dog,I am a Horse!");
}
}
class Dog extends Animal
{
public void saySomething()
{
System.out.println("woof woof,waon waon");
}
public void getTheBall()
{
System.out.println("huf huf,here it is!");
}
}
public class Main
{
public static void main (String [] args)
{
Dog dog = new Dog();
Horse horse = new Horse();
Animal animal = dog;
Animal horseAnimal = new Horse();
//upcasting
Dog upcastedAnimal = upcastToDog(animal);
dog.saySomething();
dog.getTheBall();
upcastedAnimal.saySomething();
upcastedAnimal.getTheBall();
horse.saySomething();
horse.getTheBall();
try {
Dog upcastedDog = upcastToDog(horseAnimal);
} catch (Exception ex){
System.out.println(ex.getClass().getSimpleName() + ": ObvIoUsly a horse is not a dog!");
}
}
public static Dog upcastToDog(Animal animal){
return (Dog) animal;
}
}
woof woof,waon waon
huf huf,here it is!
woof woof,here it is!
Neigh Neigh
I won't,I am a Horse!
ClassCastException: ObvIoUsly a horse is not a dog!
首先,如果尝试转换不兼容的类型,java将抛出异常.
在可以进行强制转换的情况下,将始终从实际实例调用overriden方法.在您的情况下,实例是ScottishPerson,因此即使您在BritishPerson中持有其引用,也会在ScottishPerson上调用方法.
在JLS中,这里涵盖了“Narrowing Reference Conversion”,正如他的名字所暗示的那样,只有参考被缩小或扩大(或上升或下调)而不是实例.