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

Java OOP Methods Explained

Uploaded by

kashanraja920
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)
4 views2 pages

Java OOP Methods Explained

Uploaded by

kashanraja920
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

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
[Link]("Engine started...");
}
}

public class Main {


public static void main(String[] args) {
Car myCar = new Car();
[Link](); // 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) {
[Link]("Square of 5 = " + [Link](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();
[Link]("Sum = " + [Link](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();
[Link]([Link]());
}
}

Method Overloading
Multiple methods with the same name but different parameter lists. Used for polymorphism.
class Display {
void show(int num) {
[Link]("Number: " + num);
}
void show(String text) {
[Link]("Text: " + text);
}
}

public class Main {


public static void main(String[] args) {
Display d = new Display();
[Link](100); // calls int version
[Link]("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.

You might also like