Hi All,

Greetings of the day.

Today we will explore method overloading in java.

Method Overloading - Method overloading allows the user to define a method with the same name but with different parameters and optionally with the different return types.

Rules for method overloading 

  • The overloaded method must change arguments.
  • The return type can change but it's optional.
  • The overloaded method can throw any new checked/unchecked exception, or broader checked exceptions.
  • We can change the access specifier in method overloading.
Compile Time Polymorphism / Invoking Overloaded Method

With method overloading we can have multiple methods with the same name, so which overloaded method will be invoked is decided at compile-time based on object reference and no of arguments.

So let's take an example


Now Car will extend Vehicle


Now we will create instances of Vehicle & Car and explore why method overloading is compile-time polymorphism.

O/P


Take look on 

Vehicle vehicle2=new Car();
test.driveVehicle(vehicle2);

Here at run time vehicle2 is pointing to instance is of Car but still, we get output as Drive vehicle called for vehicle... because which overloaded method will be called is decided at compile-time based on object reference which is of Vehicle type so driveVehicle method with Vehicle as an argument is called.

Let me know if you have any questions.

Also, you can refer below useful post






For Spring visit Spring Tutorial

Thanks

Happy Learning !!