Skip to the content.

Unit 5 Notes

Unit 5: Writing Classes – AP Computer Science A

🔑 Key Concepts

  • Defining classes and instance variables
  • Writing constructors
  • Accessor (get) and mutator (set) methods
  • this keyword
  • Encapsulation and visibility modifiers

🧱 Defining a Class

A class defines a blueprint for creating objects.

public class Dog {
    private String name;
    private int age;
}

🏗️ Writing Constructors

Constructors initialize the object when it is created.

public Dog(String name, int age) {
    this.name = name;
    this.age = age;
}

If no constructor is written, Java provides a default no-arg constructor.


🔍 Accessor (Getter) Methods

Return the value of a private variable.

public String getName() {
    return name;
}

✏️ Mutator (Setter) Methods

Modify the value of a private variable.

public void setAge(int newAge) {
    age = newAge;
}

📍 The this Keyword

Used to refer to the current object’s instance variables, especially when parameter names match field names.

this.name = name;

🔒 Encapsulation

  • Instance variables should be private.
  • Methods accessing or modifying variables should be public.

This protects internal state and allows controlled access.


🧪 Practice Multiple Choice (5 Questions)

1. What is the purpose of a constructor?
(A) To destroy an object
(B) To print object details
(C) To initialize instance variables
(D) To call methods
Answer: (C)


2. What is printed by this code?

public class Cat {
    private String name;
    public Cat(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
}
Cat c = new Cat("Milo");
System.out.println(c.getName());

(A) Milo
(B) name
(C) null
(D) Error
Answer: (A)


3. Why are instance variables often private?
(A) To save memory
(B) To prevent method calls
(C) To enforce encapsulation
(D) To allow global access
Answer: (C)


4. What does this.age = age; mean inside a constructor?
(A) Sets a local variable
(B) Does nothing
(C) Refers to another class
(D) Sets the instance variable age to the parameter age
Answer: (D)


5. Which method is a mutator for a variable called grade?
(A) public int getGrade()
(B) public void grade(int g)
(C) public void setGrade(int g)
(D) public int grade()
Answer: (C)