Methods / Functions in OOP (Java)
Definition
In OOP, a method (or function) is a block of code inside a class that performs a specific task. They
make programs modular, reusable, and easy to maintain.
Types of Methods in Java
Instance Method
Belongs to an object of a class. Can access instance variables.
class Car {
void startEngine() { // instance method
System.out.println("Engine started...");
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
myCar.startEngine(); // calling instance method
}
}
Static Method
Belongs to the class, not to objects. Called using the class name.
class MathUtils {
static int square(int num) { // static method
return num * num;
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Square of 5 = " + MathUtils.square(5));
}
}
Parameterized Method
Takes arguments (parameters) to perform operations. Useful for dynamic input.
class Calculator {
int add(int a, int b) { // parameterized method
return a + b;
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println("Sum = " + calc.add(10, 20));
}
}
Method with Return Type
Returns a value to the caller. The return type can be int, String, double, boolean, etc.
class Greeting {
String sayHello() { // method with return type
return "Hello, World!";
}
}
public class Main {
public static void main(String[] args) {
Greeting g = new Greeting();
System.out.println(g.sayHello());
}
}
Method Overloading
Multiple methods with the same name but different parameter lists. Used for polymorphism.
class Display {
void show(int num) {
System.out.println("Number: " + num);
}
void show(String text) {
System.out.println("Text: " + text);
}
}
public class Main {
public static void main(String[] args) {
Display d = new Display();
d.show(100); // calls int version
d.show("Hello"); // calls String version
}
}
Summary
- Instance Method → belongs to objects.
- Static Method → belongs to class.
- Parameterized Method → accepts arguments.
- Method with Return Type → returns a value.
- Method Overloading → same name, different parameters.