AP® Computer Science A · Unit 3 · Topic 3.1
Designing a Class from a Problem Description
Designing a class means reading a problem description and sorting it into two piles: nouns become fields (the data an object holds), and verbs become methods (the actions it can perform).
Every class is a blueprint for objects that need to remember something and do something. The 'remember' part is fields: variables that live inside the object and hold its state between method calls. The 'do' part is methods: the actions that read or change that state. If you pick the wrong fields, every method you write afterward has to fight the design. You'll find yourself passing extra parameters around or recomputing values that should have just been stored, because the object was never given the data it needed to answer its own questions.
The reliable way in is to read the problem description like a grammar exercise. Underline the nouns: those are candidates for fields, the pieces of information the object must carry around. Underline the verbs: those are candidates for methods, the behaviors the object must perform using its own fields. A name and a list of scores are nouns, so they become fields. Adding a score, computing an average, and depositing money are verbs, so they become methods. Each method should mostly work with the object's own fields rather than needing a pile of outside information handed to it every time.
This sorting step sets up everything else in building a class. Once fields are chosen, a constructor's job is to initialize them when an object is born, and making fields private forces all reading and changing to go through methods you control. When two classes need to share one piece of data, like a Bank holding many BankAccount objects that all reference the same interest rate, the shared value often moves up to wherever both classes can reach it, or gets passed in rather than duplicated in each object.
Key terms
- field
- A variable declared inside a class that holds part of an object's state between method calls.
- method
- A block of code inside a class that defines a behavior, usually by reading or changing the object's fields.
- state
- The current values of all of an object's fields at a given moment.
- constructor
- A special method that runs once when an object is created, setting its fields to initial values.
Watch it explained
- How it worksHow do you turn the nouns in a problem into fields and the verbs into methods?
- Worked exampleWalk me through designing a Student class for a gradebook that tracks a name and scores.
- Worked exampleFind the attributes and behaviors a BankAccount class needs for deposits and withdrawals.
- Going furtherWhat changes in the design when two classes need to share the same piece of data?
Check yourself
End of topic.