Overriding
Java Docs says:
An instance method in a subclass with the same signature (name, plus
the number and the type of its parameters) and return type as an
instance method in the superclass overrides the superclass's method.
The ability of a subclass to override a method allows a class to
inherit from a superclass whose behavior is "close enough" and then to
modify behavior as needed.
Overriding is a feature that is available while using Inheritance.
It is used when a class that extends from another class wants to use most of the feature of the parent class and wants to implement specific functionality in certain cases.
In such cases we can create methods with the same name and signature as in the parent class. This way the new method masks the parent method and would get invoked by default.
class Thought {
public void message() {
System.out.println("I feel like I am diagonally parked in a parallel universe.");
}
}
public class Advice extends Thought {
@Override // @Override annotation in Java 5 is optional but helpful.
public void message() {
System.out.println("Warning: Dates in calendar are closer than they appear.");
}
}
Overloading
Overloading in Java is the ability to create multiple methods of the same name, but with different parameters.
The main advantage of this is cleanliness of code.
Let's take the String.valueOf
method. The overloaded versions of this method are defined as:
static String valueOf(boolean b)
static String valueOf(char c)
static String valueOf(char[] data)
static String valueOf(char[] data, int offset, int count)
static String valueOf(double d)
static String valueOf(float f)
static String valueOf(int i)
static String valueOf(long l)
static String valueOf(Object obj)
This means that if we have any type of variable, we can get a String representation of it by using String.valueOf(variable)
.
If overloading was not allowed we'd have methods that look like this...
static String valueOfBoolean(boolean b)
static String valueOfChar(char c)
static String valueOfCharArray(char[] data)
static String valueOfCharArrayWithOffset(char[] data, int offset, int count)
static String valueOfDouble(double d)
static String valueOfFloat(float f)
static String valueOfInt(int i)
static String valueOfLong(long l)
static String valueOfObject(Object obj)
...which is very ugly and harder to read than the overloaded solution.