Java多态性 [英] Java Polymorphism
问题描述
这是一个出于好奇的问题。
This is a question just out of curiosity.
我知道当我们通过引用它的超类来调用子类对象的重写方法时,JVM重视了对象的类型而不是引用的类型。
I know that when we call a subclass object's overridden method by the reference of it's superclass, JVM gives importance to the type of object and not to type of reference.
这是我的简单代码:
class Animal
{
void eat()
{
System.out.println("Animal is eating...");
}
}
class Horse extends Animal
{
@Override
void eat()
{
System.out.println("Horse is eating...");
}
}
public class PolymorphismTest
{
public static void main(String...args)
{
Animal a=new Animal();
a.eat();
Animal h= new Horse();
h.eat();
}
}
正如预期的那样,我得到了输出:
As expected, I get the output :
run:
Animal is eating...
Horse is eating...
BUILD SUCCESSFUL (total time: 0 seconds)
现在我的问题是,
我们有什么办法吗?可以使用引用h来调用超类eat()方法而不是子类一个?我知道这是一个有点违反多态定律的问题,但你永远不知道何时需要这样做。
Now my question is , Is there any way that we can use reference h to call the superclass eat() method and not the subclass one? I know this is a question that is somewhat against the laws of polymorphism but you never know when the need may arise to do so.
我试图将参考h强制转换为动物但没有运气。有什么想法?
I tried to typecast the reference h to Animal but no luck. Any ideas?
推荐答案
class Horse extends Animal
{
@Override
void eat()
{
super.eat();
}
}
这篇关于Java多态性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!