7. Method

A method is a function defined in a class that describes what an object can do. It can use or modify attributes or perform tasks.

Key Points

Methods are like actions or behaviors (e.g., a person saying hello).

They can return values or perform operations like calculations.

Example: A Person class might have a method to print a greeting.

Examples

Java:

class Person {

    String name;

    void sayHello() { // Method

        System.out.println("Hello, my name is " + name);

    }

}

Python:

class Person:

    def __init__(self, name):

        self.name = name

    def say_hello(self): # Method

print(f"Hello, my name is {self.name}")