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.?
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:
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:
The choice is made based on the object type. For example,
will call the
someMethod
ofB
. You can (and should) add the @Override annotation:Now, if you accidentally change the parameters in B, the compiler will inform you, that you are not overriding someMethod() but overloading it.