AP Computer Science A · Unit 1: Using Objects & Methods
1.6 Class and Object Definitions
Anatomy of a class
A class is a blueprint for objects. It typically contains instance variables (fields storing state/data), a constructor (initializes a new object), and methods (define behavior). Instance variables should usually be declared private to enforce encapsulation, while constructors and methods used outside the class are usually public.
Constructors
A constructor has the same name as the class, no return type, and runs when an object is created with `new`. It initializes instance variables, often using parameters. If parameter names match field names, use `this.fieldName = fieldName;` to distinguish them from local parameters.
Accessors and mutators
Accessor methods (getters) return the value of an instance variable without changing it, e.g., `public int getAge()`. Mutator methods (setters) change an instance variable's value, e.g., `public void setAge(int age)`. These methods let outside code interact with private data safely, preserving encapsulation.
Key terms
- Class
- A blueprint for creating objects, defining instance variables, constructors, and methods.
- Constructor
- A special method with the same name as the class and no return type; initializes a new object's instance variables.
- Accessor method
- A method (getter) that returns the value of an instance variable without changing it.
- Mutator method
- A method (setter) that changes the value of an instance variable.
- this keyword
- Refers to the current object; used to distinguish instance variables from parameters with the same name.
Try an AP-style question
What is the relationship between a class and an object?
- They are the same thing
- A class is a type of variable
- An object is a blueprint; a class is an instance
- A class is a blueprint; an object is an instance
Show the answer
D. Instantiation.
Practice 8 AP-style questions with instant explanations, flashcards and spaced review.
Study 1.6 free in APrep