Writing Methods: AP Computer Science A Study Guide 🖥️
Introduction
Hello, aspiring coders and future tech wizards! 🔮 Ready to dive into the world of writing methods? Buckle up, because we're about to make Java magic happen! 🪄
Revisiting Pass-by-Value
Before we jump into writing methods, let’s bring back an old friend from Unit 2: pass-by-value. Think of it like lending your pencil to a friend. You give them a copy, so if they break it, your original pencil stays intact! 📝 However, if you lend them your entire pencil box, they can rearrange the contents, which affects your whole pencil collection.
When you pass a primitive variable (like int
or boolean
) to a method, you're basically giving a copy of that value. So, if the method throws a tantrum and changes the value, that change does not affect the original variable outside the method.
Now, when you pass a reference variable (like an object), the method gets a copy of the reference. This means the method can still play around with the object’s innards, just like your friend could with your pencil box. But it can't swap out the object itself for a new one, much like they can't turn your pencil box into a lunchbox.
Writing Methods
Okay, ready to make methods sing? 🎤 Let’s write some of the methods for our Assignment
and Student
classes. Pay close attention to the Javadoc comments (they're like sticky notes for programmers) and any instance variables we add along the way. These changes are in bold because we like our code to pop!
Java Example: Welcome to Class
Assignment.java
/**
* Represents an assignment that a student will complete.
*/
public class Assignment {
private boolean correctAnswer; // represents the answer to an assignment, either T/F
/**
* Makes a new assignment with one True/False question and sets the correct answer.
*/
public Assignment(boolean answer) {
correctAnswer = answer;
}
/**
* Prints details about the assignment.
*/
@Override
public String toString() {
return "This is an assignment with correct answer " + correctAnswer; // Corrected variable name
}
/**
* Grades an assignment, returns true if correct, false if incorrect.
*/
public boolean gradeAssignment(boolean studentAnswer) {
return studentAnswer == correctAnswer;
}
}
Student.java
/**
* Represents a high school student.
*/
public class Student {
private int gradeLevel; // a grade between 9-12
private String name; // the student's name in the form "FirstName LastName"
private int age; // the student's age, must be positive
private Assignment assignment; // the current assignment the student is working on
private int assignmentsComplete; // number of assignments completed
private int correctAssignments; // number of correct assignments
/**
* Makes a new student with grade level, name, and age.
*/
public Student(int gradeLev, String fullName, int ageNum) {
gradeLevel = gradeLev;
name = fullName;
age = ageNum;
assignment = null; // There is no active assignment at the moment
assignmentsComplete = 0; // no assignments complete yet
correctAssignments = 0;
}
/**
* Returns the student's grade level.
*/
public int getGradeLevel() {
return gradeLevel;
}
/**
* Returns the student's name.
*/
public String getName() {
return name;
}
/**
* Returns the current assignment the student is working on.
*/
public Assignment returnCurrentAssignment() {
return assignment;
}
/**
* Prints details about the student.
*/
@Override
public String toString() {
return name + ", a " + gradeLevel + "th grade high school student.";
}
/**
* Changes the student's name.
*/
public void setName(String fullName) {
name = fullName;
}
/**
* Changes the student's grade level.
*/
public void setGradeLevel(int gradeLev) {
gradeLevel = gradeLev;
}
/**
* Submits an assignment and updates grades.
*/
public void submitAssignment() {
boolean grade = assignment.gradeAssignment();
assignmentsComplete++;
if (grade) {
correctAssignments++;
}
assignment = null; // Reset assignment after submission
}
/**
* Calculates the student's grade as a decimal.
*/
public double getGradeDecimal() {
return (double) correctAssignments / assignmentsComplete;
}
}
Understanding Method Headers
Method headers are like the signposts in your code, guiding you to the functionality you need. They follow this typical format:
<access modifier> <return type> <method name>(<parameters>)
- Access modifiers: Can be public, private, or protected. These determine who gets to use the method - think of it as VIP access.
- Return type: What does the method give you back? It could be void, String, boolean, int, etc.
- Method name: Should be descriptive. If it’s called
doSomethingMysterious()
, expect confusion. - Parameters: What does the method need to do its job? Could be none, could be a bunch.
Sample Method Headers to Wrap Your Head Around
public static void main (String[] args)
private String sayHello()
protected static int addNums(int a, int b)
public void printSum(double a, double b, int c, boolean flag, String text)
Key Terms to Review (because, glossary vibes 📚):
- @Override: Signals that a method in a subclass is meant to override a method in its superclass.
- Access modifier: Determines visibility and accessibility of variables, methods, and classes.
- Assignment: Giving a value to a variable. Think of it as telling Java what data goes in what box.
- Boolean: A data type with only two possible values: true or false. Binary, baby!
- Instance Variables: Variables within a class but outside any method, unique to each object instance.
- Int: Stores whole numbers. Like an integer's VIP pass to the number club.
- Javadoc comments: Special comments that generate documentation for your code.
- Private: Restricts visibility to the class in which it’s defined.
- Protected: Accessible within subclasses or classes in the same package.
- Public: Open to all. Public methods are the social butterflies of the coding world.
- Return Type: The data type of the value a method returns.
- Static: Belongs to the class itself rather than any instance. Think of it as a class-level attribute.
- String: Represents text in Java, enclosed in double quotes.
- ToString(): Converts an object into its string representation.
Fun Fact!
Did you know Java was originally called Oak? Imagine saying, "I’ve got an Oak certification!" 🌳
There you have it, future code whisperers! We’ve taken a deep dive into the world of Java methods, discussed pass-by-value, written methods for two classes, and even navigated some complex terminology. Now you’re all set to make your code as sharp as a tack and just as useful! 🚀