AP Computer Science A · Unit 3: Class Creation
3.1 Anatomy of a Class
Parts of a Class
A class is a blueprint for objects. It typically contains instance variables (fields storing an object's state), constructors (methods that initialize new objects), and methods (behaviors). Instance variables are usually declared private to enforce encapsulation, while constructors and methods are usually public so other classes can use them.
Constructors
A constructor has the same name as the class and no return type, not even void. It runs when an object is created with new, initializing instance variables. A class can have multiple constructors (overloading) with different parameter lists, allowing objects to be created in different ways.
Accessor and Mutator Methods
Accessor methods (getters) return the value of an instance variable without changing it, often named getX(). Mutator methods (setters) change an instance variable's value, often named setX(value). These methods let outside code interact with private data safely, a core principle of encapsulation.
Key terms
- Instance variable
- A field declared in a class that stores an object's state; usually private.
- Constructor
- A special method with the class's name and no return type, used to initialize new objects.
- Accessor method (getter)
- A method that returns the value of an instance variable without changing it.
- Mutator method (setter)
- A method that changes the value of an instance variable.
- Constructor overloading
- Defining multiple constructors in a class with different parameter lists.
Try an AP-style question
Why are instance variables usually declared private?
- To protect the object's data
- Because Java requires it always
- To make them faster to access
- So every class can change them
Show the answer
A. Data hiding.
Practice 8 AP-style questions with instant explanations, flashcards and spaced review.
Study 3.1 free in APrep