Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function override-overload in Java

What is the difference between override and overload?

like image 830
Gandalf StormCrow Avatar asked Jan 12 '10 09:01

Gandalf StormCrow


4 Answers

  • 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.

like image 98
Jon Skeet Avatar answered Nov 13 '22 21:11

Jon Skeet


  • 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

like image 22
miku Avatar answered Nov 13 '22 20:11

miku


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.

like image 34
fastcodejava Avatar answered Nov 13 '22 20:11

fastcodejava


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 */
   }
}
like image 4
Gaim Avatar answered Nov 13 '22 19:11

Gaim