Difference between Override & Overload

Both of them only happen when difference function using same name.

  • Overloading: picking a method signature at compile time based on the number and type of the arguments specified

    Overload--在compile时抓取function signature,每个function参数列表(参数数目和数量)不同,所以区别开来。

  • Overriding: picking a method implementation at execution time based on the actual type of the target object (as opposed to the compile-time type of the expression)

    Override--在execution时选取不同的function来执行,注意这些function名称相同,参数列表相同。发生在类的继承中,子类function override夫类function,返回类型相同。

Example (with java):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Base
{
void foo(int x)
{
System.out.println("Base.foo(int)");
}
// this function will overload the function above
void foo(double d)
{
System.out.println("Base.foo(double)");
}
}

class Child extends Base
{
// this function override the function in Base
@Override void foo (int x)
{
System.out.println("Child.foo(int)");
}
}

...

Base b = new Child();
b.foo(10); // Prints Child.foo(int)
b.foo(5.0); // Prints Base.foo(double)