๐ What is a Method?
A method is a block of code that performs a specific task.
It runs only when called.
โWhy Use Methods?
To reuse code
To make the program modular and readable
To separate logic into manageable blocks
๐ง Defining and Calling Methods
๐ธ Syntax:
returnType methodName(parameters) {
// code
}๐ธ Example:
public class Main {
static void greet() {
System.out.println("Hello!");
}
public static void main(String[] args) {
greet(); // calling the method
}
}Hello!โ๏ธ Method With Parameters & Return Type
public class Main {
static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int result = add(5, 3);
System.out.println("Sum: " + result);
}
}Sum: 8๐ ๏ธ Method Overloading
Same method name, different parameters.
The compiler decides which one to call based on the arguments.
class Calculator {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
public class Main {
public static void main(String[] args) {
Calculator c = new Calculator();
System.out.println(c.add(2, 3)); // 2 parameters
System.out.println(c.add(1, 4, 5)); // 3 parameters
}
}5
10๐ Why use it?
To increase flexibility by allowing methods to handle different numbers of inputs.
๐ง Method Overriding
Method Overriding is when a child class uses the same method name, return type, and parameters as in the parent class, but provides its own code (implementation) for that method.
๐ง Why Override?
To change or extend the behavior of an inherited method from the parent class.
โ๏ธ Rules of Method Overriding:
Rule | Description |
|---|---|
โ Same method name | The method in the child class must have the same name as in the parent class. |
โ Same parameters | It must have the same parameter list (number and types). |
โ Inheritance | There must be a parent-child relationship (using |
โ Access modifier | Cannot reduce the access level (e.g., |
โ Return type | Must be the same or a subtype (called covariant return type). |
โ Cannot override |
|
โ Use of @Override | Recommended to use |
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog(); // Parent reference, child object
a.sound();
}
}Dog barks๐ Why use it?
To achieve runtime polymorphism (dynamic method binding).
๐ก What Happened Here?
Animalhas a method calledsound().Dogoverrides that method with its own version.Even though the object is of type
Animal, the Dog's method is executed โ this is runtime polymorphism.
๐ ๏ธ Why Use Method Overriding?
To customize or change the behavior of an inherited method.
To implement polymorphism (especially useful in object-oriented design).
To create more specific behavior in child classes.