Unit 3.5: Methods: How to Write Them
Methods define the behaviors of an object—the actions it can perform.
- Methods allow us to bundle logic into named, reusable blocks. This not only promotes code reuse but also makes the code more readable and easier to debug by isolating specific tasks.
Methods allow us to organize code into reusable blocks.
Void Methods
A void method performs an action but does not give any data back to the code that called it.
- The method header must include the word
void.
Task: Implementing a basic void method.
public void sayHello() {
System.out.println("Hello!"); // Just performs an action
}
Non-Void Methods
A non-void method is like a vending machine: you call it, and it "spits out" a single piece of data (a value).
- Instead of
void, the header specifies the return type (likeint,double, orString).
Task: Implementing a non-void method that returns a value.
public int getLuckyNumber() {
return 7; // Gives back an integer
}
Return by Value
When a non-void method finishes, it evaluates the expression next to the return keyword and sends that value back. This is called return by value.
Task: Returning the result of a calculation.
public double calculateTax(double price) {
return price * 0.08; // Evaluates this math and returns the result
}
The return Keyword
The return keyword immediately stops the method and sends control back to whoever called it.
- Unreachable Code: You cannot put any code after a
returnstatement in the same block. It will cause a compiler error. - Early Exit: A
returncan be used inside anifstatement or a loop to stop the method early. If it's inside a loop, it stops the loop and exits the method immediately.
Task: Using return for early method termination.
public void checkAge(int age) {
if (age < 0) {
return; // Stops the method immediately if age is invalid
}
System.out.println("Age is valid.");
}
Accessor Methods (Getters)
An accessor method allows other classes to "see" or get a copy of an object's private data.
- Accessors are always non-void methods.
Task: Implementing an accessor (getter) method.
public class Player {
private int score;
// Accessor (Getter)
public int getScore() {
return score;
}
}
Mutator Methods (Setters)
A mutator method (also called a modifier) is used to change the value of an object's data.
- Mutators are often void methods.
Task: Implementing a mutator (setter) method.
public class Player {
private int score;
// Mutator (Setter)
public void setScore(int newScore) {
score = newScore;
}
}
Method Parameters
Parameters are the inputs a method needs to do its job. They are defined in the parentheses of the method header.
Task: Defining a method with multiple parameters.
// 'name' and 'times' are parameters
public void repeatName(String name, int times) {
for (int i = 0; i < times; i++) {
System.out.println(name);
}
}
Pass by Value (Primitives)
When you pass a primitive (like int, double, or boolean) to a method, Java sends a copy of that value.
- If the method changes its local copy of the parameter, it does not change the original variable outside the method.
Task: Demonstrating that primitives are passed by value.
public void increment(int x) {
x = x + 1; // Only changes the local copy
}
// --- In main ---
int myNum = 10;
increment(myNum);
System.out.println(myNum); // Still prints 10!
Examples
Complete Class: TemperatureSensor
This example combines all the concepts of method design.
Task: Reviewing a complete class with accessors, mutators, and behaviors.
public class TemperatureSensor {
private double currentTemp;
public TemperatureSensor(double startTemp) {
currentTemp = startTemp;
}
// Accessor
public double getTemp() {
return currentTemp;
}
// Mutator with validation
public void setTemp(double newTemp) {
if (newTemp > -273.15) { // Cannot be below absolute zero
currentTemp = newTemp;
}
}
// Void method with parameter
public void logStatus(String location) {
System.out.println("Sensor at " + location + " reads: " + currentTemp);
}
}