代码:
public class X
{
public void methodA() //Base class method
{
System.out.println ("hello, I'm methodA of class X");
}
}
public class Y extends X
{
public void methodA() //Derived Class method
{
System.out.println ("hello, I'm methodA of class Y");
}
}
public class Z
{
public static void main (String args []) {
X obj1 = new X(); // Reference and object X
X obj2 = new Y(); // X reference but Y object
obj1.methodA();
obj2.methodA();
}
}
输出:
hello, I'm methodA of class X
hello, I'm methodA of class Y
正在调用对象类型的方法而不是引用类型。这两行的输出不应该是这样吗?
hello, I'm methodA of class X
hello, I'm methodA of class X
最佳答案
编译器选择与方法调用最匹配的方法签名(从所有具有相同名称的重载方法中,这些方法可用于调用该方法的变量的编译时类型)。
但是,实际执行的方法仅在运行时确定,基于调用该方法的变量所引用的实例的运行时类型。这就是方法重写的含义。”
您可能会混淆方法重载(在编译时完成)与方法覆盖(在运行时完成)。
关于java - 既然编译器根据引用类型而不是实际的对象类型来调用方法,为什么会调用对象的方法呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32586216/