java重写不生效,java – 为什么向上转换一个不改变重写方法的类?

请查看此问题,以便更好地理解上传和下传:

我也做了一个看待上传行为的例子:

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”,正如他的名字所暗示的那样,只有参考被缩小或扩大(或上升或下调)而不是实例.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值