AP Computer Science A · Topic notes
Class Creation
Key ideas, common mistakes, and a worked example for Class Creation in AP Computer Science A.
7 untimed questions from the free practice test.
Exam weighting: 10–18%
Class Creation is about writing your own classes: private instance variables, constructors, methods, static members, scope, and the this keyword. It also covers how program design affects people, including reliability and the legal use of other people's code. Free-response question 2 asks you to write a complete class.
Key ideas
- Make instance variables
privateand give access throughpublicmethods. This is called encapsulation. - A constructor has the same name as the class and no return type. It should give every instance variable a sensible starting value.
- A
staticvariable is shared by every object of the class. Astaticmethod cannot use instance variables or call instance methods without an object. - When a parameter has the same name as an instance variable, the parameter hides it. Write
this.name = name;to set the instance variable. - Java passes arguments by value. For an object, the value is a reference, so a method can change the object, but assigning a new object to the parameter does not affect the caller's variable.
Common mistakes
- Writing a return type such as
voidon a constructor, which turns it into an ordinary method. - Declaring a variable again inside the constructor (for example
int count = 0;), which creates a local variable and leaves the instance variable unchanged. - Forgetting to return a value on every path through a method that is not
void. - Making instance variables
public, or making themstaticwhen each object needs its own value.
Worked example
Write a class Counter with a private int that starts at a value given to the constructor, a method increment that adds 1 to it, and a method getCount that returns the current value.
Solution
public class Counter
{
private int count;
public Counter(int start)
{
count = start;
}
public void increment()
{
count++;
}
public int getCount()
{
return count;
}
}The instance variable is private, the constructor sets it from the parameter without a return type, and each method has the right return type: void for increment and int for getCount.
Keep going
More AP Computer Science A topics
Stuck on Class Creation?
A tutor can find the gap in one session. Book a free consultation.
Every question on this site is original and written by Bright Sprouts Academy. AP, Advanced Placement, SAT, and PSAT/NMSQT are registered trademarks of College Board, which is not affiliated with and does not endorse this site. PSAT/NMSQT is also a trademark jointly owned by College Board and National Merit Scholarship Corporation.
Last updated . Exam board and university requirements change, so always check the official specification and admissions pages.