为什么最后打印的是“我是一个儿童班”。 ?
public class Parent
{
String parentString;
public Parent()
{
System.out.println("Parent Constructor.");
}
public Parent(String myString)
{
parentString = myString;
System.out.println(parentString);
}
public void print()
{
System.out.println("I'm a Parent Class.");
}
}
public class Child extends Parent
{
public Child() {
super("From Derived");
System.out.println("Child Constructor.");
}
public void print()
{
super.print();
System.out.println("I'm a Child Class.");
}
public static void main(String[] args)
{
Child child = new Child();
child.print();
((Parent)child).print();
}
}
Output:
From Derived
Child Constructor.
I'm a Parent Class.
I'm a Child Class.
I'm a Parent Class.
I'm a Child Class.
因为这是一个例子多态性(后期绑定)。在编译时指定对象的类型Parent
因此只能调用中定义的方法Parent
。但在运行时,当“绑定”发生时,会在对象上调用该方法,该对象的类型为Child
无论代码中如何引用它。
让您感到惊讶的部分是为什么应该在运行时调用重写方法。在 Java 中(与 C# 和 C++ 不同),所有方法都是virtual因此调用了重写方法。看这个例子了解其中的差异。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)