Introduction to Methods
In our journey through class creation, we’ve learned how to describe an object's state using instance variables and how to build an object using constructors. Now, it is time to give our objects some "brains"! Methods are the actions or behaviors of a class. If a class is a blueprint for a robot, methods are the instructions that tell the robot how to move, talk, or calculate data.
Don't worry if writing code feels like learning a new language—because it is! We will break down the "grammar" of methods step-by-step so you can write them with confidence.
The Anatomy of a Method
Every method you write follows a specific pattern. Think of it like a header for a letter. It tells the computer exactly what to expect. A standard method header looks like this:
public returnType methodName(parameterList)
Let's look at each part:
1. Access Modifier (public/private): In AP CSA, most methods you write for other classes to use will be public. This means other parts of your program can "call" or use this method.
2. Return Type: This is the type of data the method sends back when it is finished. If it sends back a whole number, the type is \( \text{int} \). If it sends back nothing at all, we use the keyword void.
3. Method Name: Just like variables, we use lowerCamelCase. The name should be an action verb, like \( \text{calculateTotal} \) or \( \text{getName} \).
4. Parameter List: These are the "inputs" the method needs to do its job. They are placed inside parentheses \( ( ) \). If no inputs are needed, the parentheses stay empty.
Accessors: The "Getters"
An accessor method allows us to "read" the value of a private instance variable without changing it. Since our instance variables are usually private (to keep them safe), we need a public accessor to see what's inside.
Example: If we have a private variable \( \text{private int age;} \), the accessor would look like this:
\( \text{public int getAge()} \)
\( \{ \)
\( \text{return age;} \)
\( \} \)
Key Takeaway: Accessor methods almost always have a return type that matches the variable and a body that simply says \( \text{return} \) followed by the variable name.
Mutators: The "Setters"
A mutator method (often called a "setter") is used to change or "mutate" the value of an instance variable. This gives us control over how data is changed.
Example: To change the age, we would write:
\( \text{public void setAge(int newAge)} \)
\( \{ \)
\( \text{age = newAge;} \)
\( \} \)
Did you know? Mutators usually have a void return type because their job is to do something (change a value), not to tell you something (return a value).
Parameters: Giving the Method Input
Parameters act as temporary variables that exist only inside the method. They allow you to pass information into the method so it can perform calculations or updates.
• Formal Parameters: These are the variables defined in the method header (e.g., \( \text{int newAge} \)).
• Actual Parameters (Arguments): These are the real values you pass into the method when you call it (e.g., \( \text{myDog.setAge(5)} \)).
Quick Review: The type of the actual parameter must match the type of the formal parameter. If the method asks for an \( \text{int} \), you must give it an \( \text{int} \)!
The Return Keyword
When a method has a return type other than \( \text{void} \), it must execute a \( \text{return} \) statement. This statement does two things:
1. It stops the method immediately.
2. It sends the value back to whoever called the method.
Common Mistake: Forgetting that once a \( \text{return} \) is hit, no more code in that method will run! It’s like the "exit" door of the method.
Documentation: Preconditions and Postconditions
In AP Computer Science A, you will often see comments describing Preconditions and Postconditions. These are like a legal contract for your code.
• Precondition: A condition that must be true before the method is called. For example, a method that calculates a square root might have a precondition that the input is \( \ge 0 \). It is the caller's responsibility to make sure this is true.
• Postcondition: A condition that is guaranteed to be true after the method finishes, provided the preconditions were met. This describes the effect of the method or the value returned.
Summary Checklist
• Method Header: Does it have an access modifier, return type, name, and parentheses?
• void vs. return: If the return type is not \( \text{void} \), do you have a \( \text{return} \) statement?
• Accessors: Are you using them to "get" data?
• Mutators: Are you using them to "set" or change data?
• Parameters: Do the types in the header match the data being passed in?
Note: For more information on using the this keyword or handling object references in methods, see the next chapters in Unit 3!