Q8. What Is Method Overloading and Method Overriding?: Let's Take A Look at The Example Below To Understand It Better
Q8. What Is Method Overloading and Method Overriding?: Let's Take A Look at The Example Below To Understand It Better
Method Overloading :
In Method Overloading, Methods of the same class shares the same name but each
method must have a different number of parameters or parameters having different
types and order.
Method Overloading is to “add” or “extend” more to the method’s behavior.
It is a compile-time polymorphism.
The methods must have a different signature.
It may or may not need inheritance in Method Overloading.
Instructor-led Sessions
Real-life Case Studies
Assignments
Lifetime Access
Explore Curriculum
1 class Adder {
{
3
return a+b;
4
}
5
Static double add( double a, double b)
6
{
7 return a+b;
8 }
9 public static void main(String args[])
10 {
11
System.out.println(Adder.add(11,11));
12
System.out.println(Adder.add(12.3,12.6));
13
}}
14
Method Overriding:
In Method Overriding, the subclass has the same method with the same name and
exactly the same number and type of parameters and same return type as a
superclass.
Method Overriding is to “Change” existing behavior of the method.
It is a run time polymorphism.
The methods must have the same signature.
It always requires inheritance in Method Overriding.
1
class Car {
2
void run(){
3
System.out.println(“car is running”);
4
}
5 Class Audi extends Car{
6 void run()
7 {
9 }
You cannot override a private or static method in Java. If you create a similar method
with the same return type and same method arguments in child class then it will hide
the superclass method; this is known as method hiding. Similarly, you cannot
override a private method in subclass because it’s not accessible there. What you
can do is create another private method with the same name in the child class. Let’s
take a look at the example below to understand it better.