Overload Vs Override in Object Oriented Programming(OOP)
Overload
Overloading a method simply means two or more methods have the same method name with different arguments or parameters(compulsory) and return type(not necessary).
Example:
public class Overloads{
static String uniqueId;
public static void setUserId(String theId){
uniqueId = theId;
System.out.println(“uniqueId “ + uniqueId);
}
public static void setUserId(int number){
String numString = “” + number;
setUserId(numString);
}
public static void main(String[] args){
setUserId(555);
}
}
Override
Overriding a method simply means that a subclass redefines its inherited method(s) when it needs to change or extend the behavior of that method.
Rules for Override
- Arguments or parameters of the method in both superclass and subclass must be the same i.e same type and numbers of arguments.
- You cannot assign weaker access privilege to overridden methods. i.e You can’t override a public method and make it private.
Example:
public class Dog extends GeneralClass{
@Override
public void makeNoise(){
}
@Override
public String eat(String name){
return name;
}
}
public class GeneralClass {
public void makeNoise(){
}
public String eat(String foodName){
return foodName;
}
public void roam(){
}
public void sleep(){
}
}