Method Overloading:
- If a class have multiple methods by same name but different parameters(method signature), it is known as Method Overloading.
- Overloading happens at compile-time. The binding of overloaded method call to its definition has happens at compile-time.
- Static methods can overload which means that a class can have more than one static method of the same name.
- Overloading is being done in the same class.
- Static binding is used for overloaded methods.
- Overloading gives better performance as compared to overriding, the reason is that the binding of overridden methods is being done at runtime.
- Private and final methods can be overloaded. It means a class can have more than one private or final methods of same name.
- Return type of methods doesn't matter in case of overloading, it can be same or different but argument list should be different.
- Java Method overloading example
public class OverloadingExample {
public int sum (int a, int b){
return a+b;
}
public int sum (int a, int b, int c){
return a+b+c;
}
Method Overriding:
- If a subclass (child class) has the same method as declared in the parent class, it is known as method overriding.
- Overriding happens at runtime. The binding of overridden method call to its definition happens at runtime.
- Static methods can't be overridden, even if you declare a same static method in child class it has nothing to do with the same method of parent class.
- Overriding is all about giving a specific implementation to the inherited method of parent class.
- Dynamic binding is used for overridden methods.
- A child class cannot override the private and final methods of their base class.
- Overridden methods should be more specific return type and argument list should be same.
- Java Method overriding example:
void eat(){
System.out.println("Eating");
}
}
public class Cat extends Animal{
void eat(){
System.out.println("Eating Meat");
}
}
Nice Work (Y)
ReplyDeleteInformative (Y) Keep sharing
ReplyDeleteExcellent
ReplyDelete