Methods
Methods in Object-Oriented Programming
Learn what methods are in Object-Oriented Programming, how they define object behavior, how they work with properties, parameters, return values, constructors, encapsulation, and real-world software design.
Introduction
In Object-Oriented Programming, a method is a function or procedure that belongs to a class or object. Methods define the behavior of an object. If properties describe what an object has, then methods describe what an object can do.
For example, a Student object may have properties such as name, roll number, course, and marks. The same student object may also have methods such as displayDetails(), calculateGrade(), attendClass(), and submitAssignment().
Methods are very important because they allow objects to perform actions, process data, update properties, communicate with other objects, and implement business logic inside a program.
Simple Definition of Method
A method is a block of code written inside a class that performs a specific task. It can use object properties, receive input values, perform calculations, update object state, and return results.
In simple words:
- A method represents an action or behavior.
- A method is usually declared inside a class.
- A method can access properties of the object.
- A method can accept input through parameters.
- A method can return an output value.
- A method helps keep code organized and reusable.
Methods as Object Behavior
In Object-Oriented Programming, every object usually has three major characteristics: state, behavior, and identity. Methods are directly related to the behavior of an object.
The state of an object is stored using properties or attributes. The behavior of an object is defined using methods. When a method runs, it may read object data, change object data, perform calculations, or interact with other objects.
Car Object Behavior
A car object may have properties such as brand, color, speed, and fuel level. It may also have methods such as start(), stop(), accelerate(), brake(), and refuel().
| Object | Properties / State | Methods / Behavior |
|---|---|---|
| Student | name, rollNumber, marks, grade | study(), attendClass(), calculateGrade() |
| Car | brand, color, speed, fuelLevel | start(), stop(), accelerate(), brake() |
| Bank Account | accountNumber, holderName, balance | deposit(), withdraw(), checkBalance() |
| Product | productId, name, price, stock | displayProduct(), updateStock(), applyDiscount() |
| Book | title, author, isbn, availability | borrowBook(), returnBook(), displayBook() |
Why Do We Need Methods?
Methods are needed because they allow us to organize program logic into reusable blocks. Without methods, we may need to write the same code again and again in multiple places. This increases duplication and makes the program difficult to maintain.
Methods also help keep object-related logic inside the class. For example, in a BankAccount class, the logic for deposit and withdrawal should be inside the class because it belongs to the bank account object.
Without Methods
- Code may be repeated many times.
- Program logic becomes scattered.
- Objects cannot perform meaningful actions.
- Business rules may be difficult to manage.
- Code becomes harder to test and debug.
- Large programs become difficult to maintain.
With Methods
- Code becomes reusable and organized.
- Object behavior becomes clearly defined.
- Related logic stays inside the class.
- Business rules can be controlled properly.
- Testing and debugging become easier.
- Programs become cleaner and more maintainable.
Method Inside a Class
A method is usually written inside a class. The class defines the structure of objects, and methods define the actions that those objects can perform.
// Conceptual class with methods
Class Student
{
name
rollNumber
marks
displayDetails()
{
print name
print rollNumber
print marks
}
calculateGrade()
{
if marks >= 90
return "A"
else if marks >= 75
return "B"
else if marks >= 60
return "C"
else
return "Fail"
}
}
In this conceptual example, displayDetails() and calculateGrade() are methods of the Student class. These methods define what a student object can do.
Basic Structure of a Method
The syntax of a method can vary from one programming language to another. However, most methods usually have a name, optional parameters, a body, and sometimes a return value.
// General conceptual method structure
returnType methodName(parameters)
{
// method body
// statements
return value;
}
A method usually contains the following parts:
| Part | Meaning | Example |
|---|---|---|
| Return Type | Defines what type of value the method returns. | int, String, void, boolean |
| Method Name | The name used to call the method. | calculateGrade |
| Parameters | Input values received by the method. | amount, marks, price |
| Method Body | The block of code that performs the task. | Statements inside curly braces |
| Return Statement | Sends a result back to the caller. | return total; |
Method Parameters
Parameters are input values passed to a method. They allow a method to work with different values each time it is called. Parameters make methods more flexible and reusable.
For example, a deposit method in a BankAccount class may accept an amount as a parameter.
// Method with parameter
void deposit(double amount) {
balance = balance + amount;
}
In this example, amount is a parameter. When the method is called, the actual value is passed to the method.
// Calling method with argument
account1.deposit(1000);
account1.deposit(500);
Here, 1000 and 500 are arguments passed to the deposit method.
Parameter vs Argument
Beginners often confuse parameters and arguments. They are closely related but not exactly the same.
| Basis | Parameter | Argument |
|---|---|---|
| Meaning | Variable declared in method definition. | Actual value passed during method call. |
| Location | Written in method declaration. | Written when calling the method. |
| Example | amount in deposit(double amount) | 1000 in deposit(1000) |
| Purpose | Receives input inside method. | Sends input to method. |
Return Value in Methods
Some methods perform an action but do not return anything. Other methods calculate something and return a result. A return value is the output sent back by a method after completing its task.
For example, a method can calculate a student's grade and return it.
// Method with return value
String calculateGrade() {
if (marks >= 90) {
return "A";
} else if (marks >= 75) {
return "B";
} else if (marks >= 60) {
return "C";
} else {
return "Fail";
}
}
In this example, the method returns a String value such as A, B, C, or Fail.
Void Method
A void method performs an action but does not return a value. It may print information, update object properties, save data, or perform another task.
// Void method example
void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Marks: " + marks);
}
This method displays details but does not return any value. Therefore, its return type is void.
Example: Student Methods
Let us understand methods with a Student class. A student can display details, calculate grade, and check pass or fail status.
class Student {
String name;
int rollNumber;
int marks;
void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Roll Number: " + rollNumber);
System.out.println("Marks: " + marks);
}
String calculateGrade() {
if (marks >= 90) {
return "A";
} else if (marks >= 75) {
return "B";
} else if (marks >= 60) {
return "C";
} else {
return "Fail";
}
}
boolean isPassed() {
return marks >= 40;
}
}
public class Main {
public static void main(String[] args) {
Student student1 = new Student();
student1.name = "Rahul";
student1.rollNumber = 101;
student1.marks = 85;
student1.displayDetails();
System.out.println("Grade: " + student1.calculateGrade());
System.out.println("Passed: " + student1.isPassed());
}
}
In this example, displayDetails() is a void method, calculateGrade() returns a String, and isPassed() returns a boolean value.
Java Example of Methods
The following example shows methods in a simple BankAccount class. This example demonstrates how methods can update object properties safely.
class BankAccount {
String accountNumber;
String accountHolderName;
double balance;
void deposit(double amount) {
if (amount > 0) {
balance = balance + amount;
System.out.println("Amount deposited: " + amount);
} else {
System.out.println("Invalid deposit amount");
}
}
void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance = balance - amount;
System.out.println("Amount withdrawn: " + amount);
} else {
System.out.println("Invalid withdrawal amount");
}
}
double getBalance() {
return balance;
}
void displayAccountDetails() {
System.out.println("Account Number: " + accountNumber);
System.out.println("Account Holder: " + accountHolderName);
System.out.println("Balance: " + balance);
}
}
public class Main {
public static void main(String[] args) {
BankAccount account1 = new BankAccount();
account1.accountNumber = "A101";
account1.accountHolderName = "Ayesha";
account1.balance = 5000;
account1.deposit(1000);
account1.withdraw(1500);
account1.displayAccountDetails();
System.out.println("Current Balance: " + account1.getBalance());
}
}
This example shows that methods can control how object data is changed. The deposit and withdraw methods apply validation before updating the balance.
JavaScript Example of Methods
JavaScript also supports methods inside classes. The following example shows methods in a Product class.
class Product {
constructor(productName, price, stockQuantity) {
this.productName = productName;
this.price = price;
this.stockQuantity = stockQuantity;
}
displayProduct() {
console.log("Product Name: " + this.productName);
console.log("Price: " + this.price);
console.log("Stock Quantity: " + this.stockQuantity);
}
applyDiscount(discountAmount) {
if (discountAmount > 0 && discountAmount < this.price) {
this.price = this.price - discountAmount;
} else {
console.log("Invalid discount amount");
}
}
updateStock(quantity) {
if (quantity > 0) {
this.stockQuantity = this.stockQuantity + quantity;
}
}
getTotalValue() {
return this.price * this.stockQuantity;
}
}
const product1 = new Product("Keyboard", 1200, 10);
product1.displayProduct();
product1.applyDiscount(200);
product1.updateStock(5);
console.log("Total Stock Value: " + product1.getTotalValue());
In this JavaScript example, displayProduct(), applyDiscount(), updateStock(), and getTotalValue() are methods of the Product class.
Calling Methods Using Dot Operator
In many programming languages, methods are called using the dot operator. The dot operator connects the object name with the method name.
// Calling methods using dot operator
student1.displayDetails();
account1.deposit(1000);
product1.applyDiscount(200);
Here, each method is called using an object. The object performs the action defined by the method.
Types of Methods
Methods can be categorized in different ways depending on their purpose, return value, parameters, and how they are accessed.
Instance Methods
Methods that belong to an object
Instance methods are called using objects. They can access and modify object properties. Most methods used in beginner OOP examples are instance methods.
Static Methods
Methods that belong to the class itself
Static methods are called using the class name instead of an object. They are useful for utility operations that do not require object-specific data.
Getter Methods
Methods used to read private property values
Getter methods return the value of a property. They are commonly used in encapsulation to safely access private data.
Setter Methods
Methods used to update private property values
Setter methods update property values. They can include validation before changing the data.
Utility Methods
Methods that perform helper tasks
Utility methods perform common tasks such as formatting text, validating input, calculating totals, or converting data.
Instance Method vs Static Method
Instance methods and static methods are both useful, but they serve different purposes. Instance methods work with object data, while static methods usually work without needing a specific object.
| Basis | Instance Method | Static Method |
|---|---|---|
| Belongs To | Object | Class |
| Called Using | Object name | Class name |
| Access to Object Data | Can access object properties | Usually cannot directly access object-specific data |
| Example | student1.displayDetails() | Calculator.add(10, 20) |
| Use Case | Object-specific behavior | Common utility behavior |
Methods and Encapsulation
Methods play a very important role in encapsulation. Encapsulation means hiding internal data and allowing controlled access through methods.
For example, in a BankAccount class, the balance should not be directly changed from outside the class. Instead, the object should provide methods such as deposit(), withdraw(), and getBalance().
Poor Design
- Balance is directly accessible.
- Any code can change balance incorrectly.
- No validation is applied.
- Object state can become invalid.
- Security and reliability are reduced.
Better Design
- Balance is kept private.
- Deposit and withdraw methods control updates.
- Validation is applied inside methods.
- Object state remains valid.
- Encapsulation becomes stronger.
class BankAccount {
private double balance;
void deposit(double amount) {
if (amount > 0) {
balance = balance + amount;
}
}
void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance = balance - amount;
}
}
double getBalance() {
return balance;
}
}
In this example, the balance property is private. It can be updated only through controlled methods.
Validation Inside Methods
Methods are often used to validate data before updating object properties. Validation helps prevent invalid values from entering the object state.
For example, marks should not be negative, age should not be invalid, and bank balance should not be reduced below zero.
class Student {
private int marks;
void setMarks(int studentMarks) {
if (studentMarks >= 0 && studentMarks <= 100) {
marks = studentMarks;
} else {
System.out.println("Invalid marks. Marks must be between 0 and 100.");
}
}
int getMarks() {
return marks;
}
}
Here, the setMarks() method validates the marks before assigning the value. This protects the object from invalid data.
Methods Can Change Object State
Methods can modify the values of properties inside an object. When a method changes property values, the object's state changes.
class Car {
int speed;
void accelerate() {
speed = speed + 10;
}
void brake() {
if (speed >= 10) {
speed = speed - 10;
}
}
}
In this example, accelerate() increases the speed, and brake() decreases the speed. Both methods change the state of the Car object.
Methods Can Perform Calculations
Methods are commonly used to perform calculations. For example, calculating total price, discount, tax, grade, average marks, or salary can be done using methods.
class Product {
double price;
int quantity;
double calculateTotalPrice() {
return price * quantity;
}
double calculateDiscountedPrice(double discountAmount) {
return calculateTotalPrice() - discountAmount;
}
}
In this example, calculateTotalPrice() returns the total amount based on price and quantity. calculateDiscountedPrice() uses another method to calculate the final amount.
Methods Can Call Other Methods
A method can call another method inside the same class. This helps divide logic into smaller, reusable parts.
class Student {
int marks;
boolean isPassed() {
return marks >= 40;
}
String getResultMessage() {
if (isPassed()) {
return "Student has passed";
} else {
return "Student has failed";
}
}
}
In this example, getResultMessage() calls isPassed(). This makes the code cleaner and avoids repeating the pass/fail logic.
Real-World Example: Product Methods
In an e-commerce application, a Product object may need to display product details, apply discounts, update stock, and check availability.
| Method | Purpose | Possible Logic |
|---|---|---|
| displayProduct() | Shows product information. | Print product name, price, category, and stock. |
| applyDiscount(amount) | Reduces product price. | Check discount validity and update price. |
| updateStock(quantity) | Updates available stock. | Add or reduce stock quantity. |
| isAvailable() | Checks whether product is in stock. | Return true if stock quantity is greater than 0. |
| calculateTotalValue() | Calculates total stock value. | Multiply price by stock quantity. |
class Product {
String productName;
double price;
int stockQuantity;
void displayProduct() {
System.out.println("Product Name: " + productName);
System.out.println("Price: " + price);
System.out.println("Stock: " + stockQuantity);
}
void applyDiscount(double discountAmount) {
if (discountAmount > 0 && discountAmount < price) {
price = price - discountAmount;
}
}
boolean isAvailable() {
return stockQuantity > 0;
}
double calculateTotalValue() {
return price * stockQuantity;
}
}
Real-World Example: Bank Account Methods
A BankAccount class uses methods to protect and control important operations. Instead of directly changing the balance, we use deposit and withdraw methods.
| Method | Purpose | Validation Needed? |
|---|---|---|
| deposit(amount) | Adds money to account. | Amount should be greater than 0. |
| withdraw(amount) | Removes money from account. | Amount should be positive and less than or equal to balance. |
| getBalance() | Returns current balance. | No major validation needed. |
| displayAccountDetails() | Displays account information. | Should avoid exposing sensitive data unnecessarily. |
Method vs Function
A method and a function are similar because both are blocks of reusable code. The main difference is that a method belongs to a class or object, while a function may exist independently depending on the language.
| Basis | Function | Method |
|---|---|---|
| Location | May be written independently. | Written inside a class or belongs to an object. |
| Belongs To | Usually belongs to the program/module. | Belongs to a class or object. |
| Access to Object Data | Does not automatically access object properties. | Can access object properties. |
| Example | calculateTotal() | student1.calculateGrade() |
| OOP Context | General reusable code block. | Object behavior. |
Method vs Property
Properties and methods are both members of a class, but they have different roles. Properties store data, while methods perform actions.
| Basis | Property / Attribute | Method |
|---|---|---|
| Purpose | Stores data. | Performs action. |
| Represents | State of object. | Behavior of object. |
| Example | name, marks, balance, price | displayDetails(), deposit(), calculateGrade() |
| Question Answered | What does the object have? | What can the object do? |
| Usage | Accessed like data. | Called like an action. |
Method Naming Rules and Best Practices
Method names should clearly describe the action performed by the method. Since methods represent behavior, their names usually begin with verbs.
Method Naming Best Practices
- Use action words such as calculate, display, update, add, remove, validate, or check.
- Use meaningful names that describe what the method does.
- Follow the naming convention of the programming language.
- Use camelCase in languages where it is commonly followed.
- Avoid vague names such as doWork(), process(), handle(), or run() without clear meaning.
- Keep method names short but descriptive.
- Avoid using spaces or special characters in method names.
- Use names that make the code readable like a sentence.
| Poor Method Name | Better Method Name | Reason |
|---|---|---|
| doIt() | calculateGrade() | The better name clearly explains the task. |
| show() | displayStudentDetails() | The better name explains what is being displayed. |
| change() | updateStockQuantity() | The better name explains what is being changed. |
| check() | isProductAvailable() | The better name clearly returns a yes/no meaning. |
| calc() | calculateTotalPrice() | The better name is more readable for beginners. |
Characteristics of a Good Method
A good method should perform one clear task. If a method does too many unrelated things, it becomes hard to understand, test, and maintain.
Good Method Design Principles
- A method should have a clear purpose.
- A method should perform one main task.
- A method name should describe its action.
- A method should avoid unnecessary complexity.
- A method should use parameters when input is needed.
- A method should return a value when output is needed.
- A method should validate important input values.
- A method should avoid changing unrelated data.
- A method should be easy to test.
- A method should be reusable where possible.
Common Mistakes Beginners Make with Methods
Beginners often make mistakes while writing methods. Understanding these mistakes can help improve code quality and OOP design.
Common Mistakes
- Confusing methods with properties.
- Writing methods that do too many tasks.
- Using unclear method names such as doIt() or process().
- Not using parameters when input is needed.
- Not returning a value when result is needed.
- Repeating the same logic in multiple methods.
- Changing object data without validation.
- Making methods too long and difficult to understand.
Better Approach
- Use properties for data and methods for actions.
- Keep each method focused on one task.
- Use descriptive action-based method names.
- Use parameters for flexible input.
- Use return values for calculated results.
- Reuse methods instead of duplicating code.
- Validate important data before updating properties.
- Break long methods into smaller helper methods.
How to Identify Methods from a Problem Statement
When designing a class, methods can often be identified by looking for actions, operations, or verbs in the problem statement.
Consider this problem statement:
Possible methods from this statement are:
- borrowBook()
- returnBook()
- searchBook()
- calculateFine()
These are actions performed in the system, so they can become methods in appropriate classes.
Example: Designing Methods from a School System
Suppose we are designing a school management system. Different classes will need different methods based on their responsibilities.
| Class | Possible Methods | Purpose |
|---|---|---|
| Student | attendClass(), submitAssignment(), viewResult() | Represents actions performed by a student. |
| Teacher | takeClass(), assignMarks(), createExam() | Represents teacher responsibilities. |
| Course | addStudent(), removeStudent(), displayCourseDetails() | Manages course-related actions. |
| Exam | scheduleExam(), cancelExam(), publishExam() | Handles exam-related operations. |
| Result | calculateGrade(), displayResult(), checkPassStatus() | Handles result-related calculations and output. |
Mini Practice Activity
Try to identify possible methods from the following scenarios. This will help you think in an object-oriented way.
| Scenario | Class | Possible Methods |
|---|---|---|
| Banking System | BankAccount | deposit(), withdraw(), checkBalance(), displayAccountDetails() |
| Library System | Book | borrowBook(), returnBook(), checkAvailability(), displayBookDetails() |
| Online Shopping | Product | applyDiscount(), updateStock(), displayProduct(), calculateTotalValue() |
| School Management | Student | attendClass(), submitAssignment(), calculateGrade(), viewResult() |
| Transport System | Vehicle | start(), stop(), accelerate(), brake(), refuel() |
| Hospital System | Patient | bookAppointment(), viewReport(), payBill(), updateContactDetails() |
Frequently Asked Questions
1. What is a method in OOP?
A method is a function written inside a class. It defines the behavior or action of an object. Methods can perform calculations, update object data, display information, or return results.
2. Are method and function the same?
They are similar because both contain reusable code. The main difference is that a method belongs to a class or object, while a function may exist independently depending on the programming language.
3. What is the difference between property and method?
A property stores data, while a method performs an action. For example, marks is a property, and calculateGrade() is a method.
4. Can a method return a value?
Yes. A method can return a value such as a number, text, boolean, object, or any other data type supported by the programming language.
5. Can a method have parameters?
Yes. Parameters allow a method to receive input values. For example, deposit(amount) receives amount as input.
6. What is a void method?
A void method performs an action but does not return any value. For example, displayDetails() may print information but not return anything.
7. Why are methods important?
Methods are important because they organize logic, reduce code duplication, define object behavior, support encapsulation, and make programs easier to maintain.
8. What is an instance method?
An instance method belongs to an object and is called using an object name. It can access and modify object-specific data.
9. What is a static method?
A static method belongs to the class itself and is usually called using the class name. It is commonly used for utility operations that do not depend on object-specific data.
10. Can one method call another method?
Yes. A method can call another method inside the same class or from another object. This helps divide complex logic into smaller reusable parts.
Summary
Methods are one of the most important parts of Object-Oriented Programming. They define the behavior of objects and allow objects to perform actions. While properties store object data, methods operate on that data.
A method can display information, calculate values, update object state, validate data, return results, or communicate with other objects. Methods help make programs modular, reusable, readable, and easier to maintain.
Good method design is very important in software development. A good method should have a clear name, perform one main task, use parameters when needed, return values when useful, and validate important data.
Key Takeaway
A method is a function inside a class that defines the behavior of an object. Methods perform actions, process data, update object state, and make object-oriented programs organized, reusable, and maintainable.