Hello Jetto Net followers!
Welcome to the sixth part of our Java Object Oriented Programming (OOP) series. In the previous article, we explored the “this” keyword, which allows us to understand how objects navigate and refer to themselves. In this article, we will explore “methods” that define the behavior of objects.
What is a Method?
Methods are blocks of code that represent the operations (behaviors) that an object can perform. Just like a car can perform different actions such as accelerating, decelerating or stopping, objects perform various tasks through methods. Methods are a set of commands that are put together to perform a specific task.
How to define a method?
To define a method in Java, we follow these steps:
- Access Modifier: Determines the scope from which the method is accessible (public, private, protected or default).
- Return Type: Specifies the data type of the value the method will return (int, String, boolean, etc.). If the method does not return a value, void is used as the return type.
- Method Name: Specifies the name of the method. Method names usually start with a lowercase letter and must be meaningful.
- Parameter List: Defines the variables that represent the values (arguments) to be passed to the method. Parameters are specified as data type and name pairs.
- Method Body: The block of code that contains the operations that the method will perform. The method body is written in curly braces ({}).
NOTE: I will prepare a separate article for item 1!
public class Car {
public void accelerate(int accIncrement) {
// Acceleration operations
}
public int showCcurrentSpeed() {
// Calculate current speed and return
return currentSpeed; // methods that return a value must include this expression!
}
}
Display More
How to Call a Method?
To call a method, parentheses (()) are used after the method name. If the method takes parameters, the parameter values are given in parentheses.
Car myCar = new Car();
myCar.accelerate(20); // call the accelerate() method with parameter 20
int currentSpeed = myCar.showCcurrentSpeed(); // call the showCcurrentSpeed() method and assign the return value to the currentSpeed variable
Advantages of Methods
- Code Reusability: Methods can be defined once and called many times instead of writing the same operation over and over again.
- Code Readability: Methods increase the readability of code by breaking complex operations into smaller and more meaningful parts.
- Maintainability of Code: Methods make code easier to understand and bugs can be found and fixed faster.
Conclusion
Methods in Java are powerful tools that allow us to define the behavior of objects. By using methods, we can make our code more organized, understandable, reusable and maintainable. You can write your questions or thoughts in the comments section.
In our next article, we will continue to explore other important concepts of OOP. Stay tuned!