AP Computer Science A Unit 5 Review with Java Codes
1. Anatomy of a Class
public class Dog {
// Fields (properties) of the class
private String breed;
private int age;
// Constructor
public Dog(String breed, int age) {
this.breed = breed; // Initializing the breed
this.age = age; // Initializing the age
}
// Methods (behaviors) of the class
public void bark() {
System.out.println("Woof!");
}
public String getBreed() {
return breed; // Accessor method for breed
}
public void setBreed(String breed) {
this.breed = breed; // Mutator method for breed
}
}
2. Constructors
public class Dog {
private String breed;
private int age;
// Constructor
public Dog(String breed, int age) {
this.breed = breed; // Initialize breed
this.age = age; // Initialize age
}
}
3. Documentation with Comments
public class Dog {
// Field for dog's breed
private String breed;
// Constructor
public Dog(String breed) {
this.breed = breed; // Initialize breed
}
// Method for dog to bark
public void bark() {
System.out.println("Woof!");
}
}
4. Accessor Methods
public class Dog {
private String breed;
public Dog(String breed) {
this.breed = breed; // Initialize breed
}
// Accessor method for breed
public String getBreed() {
return breed;
}
}
5. Mutator Methods
public class Dog {
private String breed;
public Dog(String breed) {
this.breed = breed; // Initialize breed
}
// Mutator method for breed
public void setBreed(String breed) {
this.breed = breed;
}
}
6. Writing Methods
public class Dog {
private String breed;
private int age;
public Dog(String breed, int age) {
this.breed = breed;
this.age = age;
}
// Method for dog to bark
public void bark() {
System.out.println("Woof!");
}
// Method to calculate dog's age in human years
public int calculateHumanAge() {
return age * 7;
}
}
7. Static Variables and Methods
public class Dog {
private String breed;
private int age;
// Static variable
private static int dogCount = 0;
// Constructor
public Dog(String breed, int age) {
this.breed = breed;
this.age = age;
dogCount++; // Increment dog count when a new dog is created
}
// Static method to get dog count
public static int getDogCount() {
return dogCount;
}
}
8. Scope and Access
public class Dog {
// Private variable, accessible only within the class
private String breed;
// Public constructor, accessible from outside the class
public Dog(String breed) {
this.breed = breed; // Initialize breed
}
// Public method to get breed, accessible from outside the class
public String getBreed() {
return breed;
}
}
9. this Keyword
public class Dog {
private String breed;
private int age;
// Constructor
public Dog(String breed, int age) {
this.breed = breed; // Use 'this' to refer to instance variable
this.age = age;
}
// Accessor method for breed
public String getBreed() {
return this.breed;
}
}