Java

Method Overloading vs Method Overriding in Java

The overriding and overloading are the two important concepts in OOP (Object Oriented Programming) they may be confusing at the start but once your go on it will become easy.

This article gives you the difference between method overloading and overriding.

1. Definitions




Overloading occurs when two or more methods in one class have the same method name but different parameters.

Overriding means having two methods with the same method name and parameters (i.e.,method signature). One of the methods is in the parent class and the other is in the child class. Overriding allows a child class to provide a specific implementation of a method that is already provided its parent class.

2. Overriding vs. Overloading

Here are some important facts about Overriding and Overloading:

1). The real object type in the run-time, not the reference variable’s type, determines which overridden method is used at runtime. In contrast, reference type determines which overloaded method will be used at compile time.
2). Polymorphism applies to overriding, not to overloading.
3). Overriding is a run-time concept while overloading is a compile-time concept.

3. An Example of Overriding

Here is an example of overriding. After reading the code, guess the output.

Output:

In the example above, the dog variable is declared to be a Dog. During compile time, the compiler checks if the Dog class has the bark() method. As long as the Dog class has thebark() method, the code compilers. At run-time, a Hound is created and assigned to dog. The JVM knows that dog is referring to the object of Hound, so it calls the bark() method ofHound. This is called Dynamic Polymorphism.

4. An Example of Overloading

In this overloading example, the two bark method can be invoked by using different parameters. Compiler know they are different because they have different method signature (method name and method parameter list).

Take time to share feedback in the comment section.

Leave a Comment