What is the difference between override and overload?
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
.
Overloading of methods is a compiler trick to allow you to use the same name to perform different actions depending on parameters.
Overriding a method means that its entire functionality is being replaced. Overriding is something done in a child class to a method defined in a parent class.
src: http://www.jchq.net/tutorial/06_02Tut.htm
Overloading :
public Bar foo(int some);
public Bar foo(int some, boolean x); // Same method name, different signature.
Overriding :
public Bar foo(int some); // Defined in some class A
public Bar foo(int some); // Same method name and signature. Defined in subclass of A.
If the second method was not defined it would have inherited the first method. Now it will be replaced by the second method in the subclass of A.
Overload - similar signature - same name, different parameters
void foo() {
/** overload */
}
void foo( int a ) {
/** overload */
}
int foo() {
/** this is NOT overloading, signature is for compiler SAME like void foo() */
}
Override - you can redefine method body when you inherit it.
class A {
void foo() {
/** definition A */
}
}
class B extends A {
void foo() {
/** definition B, this definition will be used when you have instance of B */
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With