Overloading: picking a method signature at compile time based on the number and type of the arguments specified
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)
For example:
class Base
{
void foo(int x)
{
System.out.println("Base.foo(int)");
}
void foo(double d)
{
System.out.println("Base.foo(double)");
}
}
class Child extends 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)
Both calls are examples of overloading. There are two methods called foo
, and the compiler determines which signature to call.
The first call is an example of overriding. The compiler picks the signature "foo(int)" but then at execution time, the type of the target object determines that the implementation to use should be the one in Child
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…