Chapter 6 Java Methods
Understanding Java Methods¶
Java methods, often referred to as functions in other programming languages, are blocks of code designed to perform a specific task. They are the building blocks of functional programming in Java, bringing the concept of modularity, reusability, and clarity.
Why do we use methods?
-
Code Reusability: Instead of writing the same code again and again, we write a method once and call it wherever required. This makes the code less cluttered and more efficient.
-
Code Organization: With methods, we can organize our code in a more structured way. It helps in breaking down a large and complex problem into smaller and manageable pieces. Each method does a specific task, contributing to the solution of the complex problem.
Declaring and Calling a Method¶
Declaring a method in Java involves its return type, name, and parameters. The syntax looks like this:
accessModifier returnType methodName(parameters) {
// method body
}
Let's consider an example:
public int square(int num) {
return num * num;
}
This method square accepts an integer as a parameter and returns the square of that number.
Calling a method means triggering the method to execute its task. We do this using the method's name followed by parentheses (), inside which we pass the arguments.
int result = square(7);
System.out.println(result); // Output: 49
Constructors in Java¶
In Java, constructors are special methods used to initialize objects. They are automatically called when an object is created.
Why do we use constructors?
- Object Initialization: Constructors help in initializing an object's state. We can assign values to the object's properties using the constructor.
Declaring a Constructor¶
A constructor is declared with the same name as the class and doesn't have a return type. Its access level can be public, private, protected, or default, just like methods.
public class Car {
String model;
// This is the constructor
Car(String carModel) {
model = carModel;
}
}
This Car class has a constructor that takes a string as a parameter and assigns it to the model field.
To create a new Car object, we call the constructor, passing the necessary parameters.
Car myCar = new Car("Mustang");
The constructor is automatically invoked when we use the new keyword. The provided argument "Mustang" is passed to the Car constructor and initializes the model of myCar.
In conclusion, methods and constructors are pillars of Java. They help structure the code into manageable chunks, making it more readable and reusable.