Method Overloading:
Method overloading means there are multiple methods, within a class, with same name but with different parameters.
Method return types may or may not be same.
Method overloading may happen inside a class or inside a subclass.
public class Main {
public static void main(String[] args) {
Animal a =new Animal();
a.Horse();
a.Horse(“black”);
a.Horse(10);
}
}
class Animal {
private String color;
public void Horse() {
System.out.println(“The horse’s name is Jakob”);
}
public void Horse(String color) {
System.out.println(“The color of the horse is “+ color);
}
public void Horse(int age) {
System.out.println(“The age of the horse is “+ age);
}
}
Method Overriding:
If the method name in sub-class is same as the super class method name and the parameter passed to these methods are the same , then method overriding will happen.The outcomes of the two methods are different.
Method overriding happens in subclass.
Restrictions – The constructor, the private and final methods can not be overridden.
public class Tea {
public static void main(String[] args) {
Lemontea t= new Lemontea();
t.tasteOfTea(“normal”);
}
}
class Specialtea{
public void tasteOfTea(String tea_type) {
System.out.println(“The type of tea is “+ tea_type);
}
}
class Lemontea extends Specialtea{
//Method overriding
@Override
public void tasteOfTea(String tea_type) {
System.out.println(“The tea type “+ tea_type+ ” has been changed to lemon tea now.”);
}
}