为什么在本示例中未调用子类方法,因为它在Java中是动态多态性中被调用的? [英] Why child class method is not called in this example as it is called in dynamic polymorphism in Java?

查看:32
本文介绍了为什么在本示例中未调用子类方法,因为它在Java中是动态多态性中被调用的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经做过一些研究,但是在下面的示例中我无法找到为什么运行时多态性没有发生的原因.根据我的理解,应该在孩子中调用foo(int a).但是输出是"Parent with long".有人可以对此加以解释吗?

I have done some research but I am no able to find why runtime polymorphism is not taking place in example below. According to my understanding foo(int a) should have been called in child.But out put is "Parent with long".Can someone throw light on this?

class Parent {
public void foo() throws RuntimeException {
    System.out.println("Parent with no Parameter");
}

public void foo(long a) {
    System.out.println("Parent with long");
}
}

class Child extends Parent {
public void foo() {
    System.out.println("Child with no parameter");
}

public void foo(int a) throws RuntimeException {
    System.out.println("Child with int");
}
}

class Demo {
public static void main(String... args) {
    Parent p = new Child();
    int a = 10;
    p.foo(a);
}
}

输出:

父母长

推荐答案

您所拥有的是 Parent 和2种方法: foo(long) foo().还有从其父级继承的 Child ,并添加了两个新的不同方法: foo(int)和(其中一个重载了现有方法)foo()(该代码将覆盖继承的代码).

What you have is Parent with 2 methods: foo(long) and foo(). And Child that inherits from its parent and add two new different methods: foo(int) and (that one overloads existing methods) foo()(that one overrides the inherited one).

有不同的机制:在编译时发生什么,在运行时发生什么.在编译时,编译器只会相应地查看变量类型.在运行时,执行环境.将查看对象类型.

There is different mechanisms: what happens at compile time, and what happens at runtime. At compile time, the compiler will only look accordingly to variable types. At runtime, the execution env. will look at object types.

现在,当编译调用 p.foo(a)时,编译器将查看 p 的类型,即 Parent 并查看在 Parent 类中获取相应的可调用方法.它会找到 foo(long),然后使用从 int long的强制转换生成对方法 foo(long)的动态调用.到运行时的真实对象(类型为 Child ).但是此对象只有一种这样的方法,即 Parent 中的一种,因此将调用此方法.

Now when compiling the call p.foo(a), compiler will look at the type of p, which is Parent and look in Parent class for a corresponding callable method. It finds foo(long) and then generates a dynamic call to a method foo(long) with a cast from int to long to the real object at runtime (of type Child). But this object has only one such method, the one in Parent, so this one will be called.

Child foo(int)更改为 foo(long),您将拥有所需的内容.

Change Child's foo(int) into foo(long) and you will have what you wanted.

这篇关于为什么在本示例中未调用子类方法,因为它在Java中是动态多态性中被调用的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆