Overriding and Overloading in Java
In Java, method overriding and method overloading are two important concepts in Object-Oriented Programming. They allow you to define methods with the same name but different parameters or implementations in different classes.
Method Overriding
Method overriding is the process of defining a new implementation for an inherited method from a parent class in a child class. The child class provides its own implementation, which may be different from the parent class.
Here's an example to illustrate method overriding:
1public class Animal {
2
3 public void makeSound() {
4 System.out.println("The animal makes a sound.");
5 }
6
7}
8
9public class Dog extends Animal {
10
11 public void makeSound() {
12 System.out.println("The dog barks.");
13 }
14
15}
16
17public class Main {
18
19 public static void main(String[] args) {
20 Animal animal = new Animal();
21 animal.makeSound(); // Output: The animal makes a sound.
22
23 Dog dog = new Dog();
24 dog.makeSound(); // Output: The dog barks.
25 }
26
27}
In the above example, the Animal
class has a method makeSound()
. The Dog
class inherits this method but provides its own implementation. When you create an object of type Dog
and call the makeSound()
method, it will print "The dog barks." instead of "The animal makes a sound.".
Method Overloading
Method overloading is the process of defining multiple methods with the same name but different parameters within the same class. The methods can have different parameter types, different parameter counts, or both.
Here's an example to illustrate method overloading:
1public class Calculator {
2
3 public int add(int a, int b) {
4 return a + b;
5 }
6
7 public double add(double a, double b) {
8 return a + b;
9 }
10
11}
12
13public class Main {
14
15 public static void main(String[] args) {
16 Calculator calculator = new Calculator();
17 int sum1 = calculator.add(2, 3); // Output: 5
18 double sum2 = calculator.add(2.5, 3.7); // Output: 6.2
19 }
20
21}
In the above example, the Calculator
class has two add()
methods with different parameter types (int
and double
). When you call the add()
method with two int
arguments, the int
version of the method will be executed. When you call the add()
method with two double
arguments, the double
version of the method will be executed.
Method overriding and method overloading are powerful techniques in Java that allow you to write more flexible and expressive code. They help in designing classes with different behaviors based on the context or requirements of the program.