在下面的程序中,我在类 A 中的一个方法重载了 3 次,然后在子类 B 中,所有 3 个重载方法都被覆盖。
obj3 是一个具有引用类型 A(超类)和对象类型 B(子类)的对象,它在执行时从 B 调用方法,这是预期的行为。
由于此代码中都存在重载和覆盖,这是否意味着它在编译时执行静态绑定(到 A 类中的匹配方法),然后在运行时执行动态绑定(到 B 类中的方法)。它们可以同时发生吗?
我的假设是,这是动态绑定的经典案例,因为我认为“绑定”是一种永久性操作,但同行建议它是一起的(首先是静态的,然后是动态的)。
class A{
public void method(Integer n){
System.out.println("Integer: "+n);
}
public void method(String s){
System.out.println("String: "+s);
}
public void method(String s, Integer n){
System.out.println("String: "+s+" Integer: "+n);
}
}
class B extends A{
public void method(Integer n){
System.out.println("Integer(from B): "+n);
}
public void method(String s){
System.out.println("String(from B): "+s);
}
public void method(String s, Integer n){
System.out.println("String(from B): "+s+" Integer(from B): "+n);
}
}
public class Test{
public static void main(String[] args){
A obj1 = new A();
B obj2 = new B();
A obj3 = new B();
System.out.println("Integer form of method");
// Integer form of method
System.out.println("Ref A Obj A");
// Ref A Obj A
obj1.method(1);
// Integer: 1
System.out.println("Ref B Obj B");
// Ref B Obj B
obj2.method(2);
// Integer(from B): 2
System.out.println("Ref A Obj B");
// Ref A Obj B
obj3.method(3);
// Integer(from B): 3
}
}