Quiz: what’s the result of below code?

本文通过一个简单的Java示例展示了方法重写与重载的区别。在继承关系中,子类重写了父类的方法但因参数不同实际为重载,导致调用行为不符合预期。此例子强调了理解方法签名的重要性。
public class Quiz {
public static void main(String[] args)
{
A aa = new A();
B bb = new B();
aa.f();
bb.f();
}
}
class A
{
public void f()
{
System.out.printf(“AAAA\n”);
}
}

class B extends A
{
public void f(int i)
{
System.out.printf(“BBBB\n”);
}
}

Look very simple. You may think result is:
AAAA
BBBB
Then, it’s wrong.

B extends A, and has a f() method as A. You may think it’s “overriding”, but be careful, the f() method in B has a parameter “int i”. So in fact it’s not an “overriding”, but a “overloading” of B’s method f() — Override need same parameter(s).
In the main, we called aa.f() and bb.f(). For aa.f(), easy, just output “AAAA”.
But for bb.f(), this call doesn’t have a parameter. so in fact it’s trying to call the f() which is extended from A.
So the result is:
AAAA
AAAA

转载于:https://www.cnblogs.com/backpacker/archive/2012/04/24/2467432.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值