AP Computer Science A › Unit 3
Unit 3 moves from using classes to writing them. You will design a class with private instance variables, constructors, and methods, and learn about static members, scope, access, and the this keyword. The free-response section includes a class design question, where you write a complete class from a description and examples. A common error is redeclaring an instance variable as a local variable inside a constructor, so the field never gets set. Students also confuse static and instance members, or try to return a value from a void method.
These are taken from the Regular set, with the answer and explanation shown.
1. A class Employee has a private instance variable salary and public methods getSalary and raise. Which of the following best describes the benefit of this design?
salary is shared by all Employee objectssalary can be read and changedsalary directlyAnswer: B. Keeping the variable private is data encapsulation. Code outside of the class must go through the public methods, so the class decides what is allowed, for example whether a raise can be negative.
Common trap: Choosing "other classes can read and change salary directly". Private variables are exactly the ones other classes cannot use directly.
2. Consider the following class.
Answer: C. twice(addOne(3)) is twice(4), which is 8. addOne(twice(3)) is addOne(6), which is 7. The sum is 15.
Common trap: Choosing 16. That treats both halves as twice(addOne(3)). The order of the calls matters.
3. Consider the following code segment.
Answer: D. Each for loop declares its own loop variable, whose scope is only that loop, so the same name can be used again in the next loop. The first loop adds 0 + 1 + 2 = 3, and the second adds 5 + 6 = 11, for a total of 14.
Common trap: Choosing "does not compile because i is declared twice". The two declarations have separate scopes, so there is no conflict.