Can you explain the result of the following example? Oh, my!

class Base {
  public boolean foo(Base b) { 
return true;
}
}
class Sub extends Base {
public boolean foo(Sub s) {
return false;
}
}

public class Test {
public static void main(String argv[]) {
Base bb = new Base();
Base bs = new Sub();
Sub ss = new Sub();

System.out.println(bb.foo(bb)); //true

System.out.println(bs.foo(bs)); //true ???
System.out.println(bs.foo(ss)); //true ???
System.out.println(bs.foo(bb)); //true ???
System.out.println(ss.foo(bs)); //true ???
System.out.println(ss.foo(bb)); //true ???

System.out.println(ss.foo(ss)); //false
}
}
A: The foo methods are overloaded in the Sub. In Base, there is only one foo method, and it is not overridden by the Sub!
Overloading is fundamentally different then overriding. There is no polymorphism or dynamic binding here!!! All decisions are made at compile time!!! See detailed explanation in the same code below, documented!
class Base { 
// There is only one foo method in Base!!!
public boolean foo(Base b) {
return true;
}
}
class Sub extends Base {
// differnt signature, method overloading
// there are 2 foo methods in the Sub
public boolean foo(Sub s) {
return false;
}
}

public class Test {
public static void main(String argv[]) {
// bb is a Base ref to the compiler, Base obj at runtime
Base bb = new Base();
// bs is a Base ref to the compiler, Sub obj at runtime
Base bs = new Sub();
// ss is a Sub ref to the compiler, Sub obj at runtime
Sub ss = new Sub();

// All these 4 lines are Base ref
// call Base.foo(Base) method, and only one foo available
// bs is a Base ref, and ss ISA Base ref too
// Everything is fine!!!
System.out.println(bb.foo(bb)); //true
System.out.println(bs.foo(bs)); //true
System.out.println(bs.foo(ss)); //true
System.out.println(bs.foo(bb)); //true

// bb, bs are both Base refs to Compiler
// ss is a Sub ref
// call Sub.foo(Base) which is inherited from Base
System.out.println(ss.foo(bs)); //true
System.out.println(ss.foo(bb)); //true

// no doubt about this one, am I right?
System.out.println(ss.foo(ss)); //false
}
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值