Free-Response Patterns
Identify recurring FRQ patterns including class design, array processing, ArrayList mutation, 2D arrays, and method decomposition.
A lesson of AP Computer Science A, in AP CS A Exam Readiness, about 10 minutes.
Classes, Objects, and Methods
By the end of this lesson, you will be able to define classes with instance variables and methods, create objects using constructors, and understand the principles of encapsulation.
Object-Oriented Programming Overview
Java is an object-oriented language. The fundamental idea: model the world as objects that have:
- State (instance variables/fields) — the data an object holds
- Behavior (methods) — what the object can do
Class: a blueprint or template for creating objects.
Object (instance): a specific thing created from a class.
Analogy: a class is like an architectural blueprint; an object is the actual house built from that blueprint.
Defining a Class
public class Dog {
// Instance variables (fields)
private String name;
private int age;
private String breed;
// Constructor
public Dog(String name, int age, String breed) {
this.name = name;
this.age = age;
this.breed = breed;
}
// Methods
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void bark() {
System.out.println(name + " says: Woof!");
}
public String toString() {
return name + " is a " + age + "-year-old " + breed;
}
}
Creating Objects (Instantiation)
// In a separate class or the main method:
Dog myDog = new Dog("Rex", 3, "German Shepherd");
Dog yourDog = new Dog("Bella", 5, "Golden Retriever");
// Calling methods on objects:
myDog.bark(); // "Rex says: Woof!"
System.out.println(yourDog.getName()); // "Bella"
System.out.println(myDog.getAge()); // 3
System.out.println(myDog); // calls toString(): "Rex is a 3-year-old German Shepherd"
new keyword: creates a new object in memory; calls the constructor.
Constructors
public Dog(String name, int age) {
this.name = name; // this.name = instance variable; name = parameter
this.age = age;
}
Constructor: a special method called when an object is created with .