Java Methods, Method Overloading, and Method Overriding
1. Methods in Java
A method is a block of code that performs a specific task. It is executed when called.
Syntax:
returnType methodName(parameters) {
// code
2. Method Overloading
Definition: Method Overloading means having multiple methods in the same class with the same name but
different parameter lists (different number or type of parameters).
Key Points:
- Happens within the same class.
- Differentiated by method signature.
- Return type can be same or different, but doesn't matter for overloading.
Example:
class Calculator {
int add(int a, int b) {
return a + b;
double add(double a, double b) {
return a + b;
int add(int a, int b, int c) {
return a + b + c;
Java Methods, Method Overloading, and Method Overriding
3. Method Overriding
Definition: Method Overriding means redefining a method in a subclass that already exists in the superclass.
Key Points:
- Occurs in an inheritance hierarchy (parent-child classes).
- Method name, parameters, and return type must be the same.
- The @Override annotation is recommended.
Example:
class Animal {
void sound() {
System.out.println("Animal makes sound");
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");