Java – What’s the difference between overloading a method and overriding it in Java

javaobject-oriented

What's the difference between overloading a method and overriding it in Java?

Is there a difference in method signature, access specifier, return type, etc.?

Best Answer

To overload a method with a new method, the new method should have a different signature. I.e. two overloaded methods have the same name, but different parameters. Here's an example of two overloaded methods:

boolean isOdd(int number) { ... };
boolean isOdd(float number) { ... };

Based on the parameter types, the corresponding method will be called. Note that changing the return type is not enough (though you can do this additionally).

When a method is overridden, then the new method has the same signature and replaces the overridden method in some cases. Here's an example of an overridden method:

public class A 
{
     public void someMethod() { ... }
}

public class B extends A
{
     public void someMethod() { ... }
}

The choice is made based on the object type. For example,

A someA = new B();
someA.someMethod();

will call the someMethod of B. You can (and should) add the @Override annotation:

public class B extends A
{
     @Override
     public void someMethod() { ... }
}

Now, if you accidentally change the parameters in B, the compiler will inform you, that you are not overriding someMethod() but overloading it.