0% found this document useful (0 votes)
41 views2 pages

Method Overloading and Method Overriding

Uploaded by

akramshaik2004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views2 pages

Method Overloading and Method Overriding

Uploaded by

akramshaik2004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Method Overloading and Method Overriding

1. Method Overloading
Method overloading occurs when two or more methods in the same class have the same name but differ in
their parameter lists (different number of parameters, different types of parameters, or both). It is a form of
compile-time polymorphism.
Example of Method Overloading:
java
Copy code
class Calculator {
// Method to add two integers
int add(int a, int b) {
return a + b;
}

// Overloaded method to add three integers


int add(int a, int b, int c) {
return a + b + c;
}

// Overloaded method to add two double values


double add(double a, double b) {
return a + b;
}

public static void main(String[] args) {


Calculator calc = new Calculator();

System.out.println(calc.add(5, 10)); // Calls the method with 2 integers


System.out.println(calc.add(5, 10, 15)); // Calls the method with 3 integers
System.out.println(calc.add(5.5, 10.5)); // Calls the method with 2 doubles
}
}
Output:
15
30
16.0
• Method Overloading: The add method is overloaded with different parameter types and number of
parameters. The compiler decides which method to call based on the arguments passed.

2. Method Overriding
Method overriding occurs when a subclass provides a specific implementation for a method that is already
defined in its parent class. It is a form of runtime polymorphism. The method in the subclass should have
the same name, return type, and parameters as in the parent class.
Example of Method Overriding:
java
Copy code
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
// Overriding the sound method
void sound() {
System.out.println("Dog barks");
}
public static void main(String[] args) {
Animal animal = new Animal();
Dog dog = new Dog();
animal.sound(); // Calls the parent class method
dog.sound(); // Calls the overridden method in Dog
}
}
Output:
Animal makes a sound
Dog barks

You might also like