![](/img/trans.png)
[英]Polymorphism + Overloading - How to make a child class' polymorphic/overloaded method get called?
[英]Why child class method is not called in this example as it is called in dynamic polymorphism in Java?
我已经做过一些研究,但是在下面的示例中我无法找到为什么运行时多态性没有发生的原因。 根据我的理解,应该在孩子中调用foo(int a)。但是输出的是“ Parent with long”。有人可以对此加以说明吗?
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);
}
}
输出:
父母长
仅当方法具有完全相同的签名(相同数量和类型的参数)时,多态性才适用。
您拥有的是具有2种方法的Parent
: foo(long)
和foo()
。 从其父级继承并添加两个新的不同方法的Child
: foo(int)
和(该方法重载了现有方法) foo()
(该方法覆盖了继承的方法)。
有不同的机制:什么在编译时发生,什么在运行时发生。 在编译时,编译器只会相应地查看变量类型。 在运行时,执行环境。 将查看对象类型。
现在,在编译调用p.foo(a)
,编译器将查看p
的类型(即Parent
并在Parent
类中查找相应的可调用方法。 它找到foo(long)
,然后在运行时(类型为Child
)从int
到long
转换为真实对象的方法foo(long)
的动态调用。 但是此对象只有一个这样的方法, Parent
的一个,因此将调用此方法。
将Child
的foo(int)
更改为foo(long)
,您将拥有所需的内容。
正如您所说,多态性是正确的。 您所看到的是编译时多态性,这是超载的。
Child的方法已经在编译时确定,因为在parent中没有定义等效的方法,也没有应用ovveriding(运行时多态)。
在Java中,多态性从头到尾发挥作用。..您看到..在创建子对象时,实际上是在创建专利对象..当您的孩子扩展到专利时,它将永远不会出错。 所以..您实际上是在创建一个专利对象..根本不是一个子对象..这就是为什么它执行父母的方法..如果您想了解多态性是如何工作的..则只需创建Child对象= new Child() 。 然后传递Long或int变量。希望对您有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.