Below is the complete review sheet for AP Computer Science A – Unit 5: Writing Classes, combining both parts of Lesson 5 into one cohesive document.
Member Type | Keyword | Belongs To | Accessible By | Shared? |
---|---|---|---|---|
Class Variable | static |
The class | Static & non-static methods | Yes (one copy) |
Instance Variable | (none) | Each object | Non-static methods | No (per instance) |
accessModifier [static] returnType methodName(parameterList) {
// method body
}
public
(anywhere) or private
(within class).static
marks class methods; omit for non-static.void
(no return) or any primitive/object type.private
for encapsulation; getters/setters allow controlled access.public class Student {
private int studentId; // instance field
private static String mascot; // class field
// Getter for instance field
public int getStudentId() {
return studentId;
}
// Setter for instance field
public void setStudentId(int newId) {
studentId = newId;
}
// Getter for class field
public static String getMascot() {
return mascot;
}
// Setter for class field
public static void setMascot(String newMascot) {
mascot = newMascot;
}
}
new
an object.public class Robot {
private static String fuelSource;
private String name;
// No-arg constructor
public Robot() {
fuelSource = "Electricity";
randomName();
}
// Overloaded constructor
public Robot(String newName) {
fuelSource = "Electricity";
name = newName;
}
}
this
Keywordthis
refers to the current object.java
private int x;
public void setX(int x) {
this.x = x;
}
* Call another constructor:
java
public Robot() {
this("Wall-E"); // must be first line
}
* Pass current object:
java
otherObj.process(this);
Define multiple methods with same name but different signatures:
✔ Valid overload if one of:
void outputAnswer() { … }
void outputAnswer(int x) { … }
void outputAnswer(int x, int y) { … }
✖ Invalid overload if signatures collide (even with different return types or parameter names).
public static void main(String[] args) {
int a = 1; // scope: entire method; lifetime: until main ends
{
int b = 2; // scope: this block only; lifetime: block's execution
}
for (int c = 0; c < 3; c++) {
int d = c; // scope & lifetime: each iteration of this loop
}
}
Practice creating classes, constructors, getters/setters, and overloaded methods. Trace memory with this
and variable scope to solidify your understanding!