Writing a Class
Writing your own class is like writing a recipe. You define a collection of ingredients (the attributes or state) and a set of instructions (methods or operations) for working with the ingredients. Once written, your recipe can be used by others to make instances of your delicacy.
One nuance that is sometimes hard to appreciate is that, while writing your recipe, you are not actually baking anything. You are only describing how a recipe is to hypothetically be baked. Someone else must come along and use your recipe (make instances of your class). That someone else may be you, or it may be a coworker, or it may be someone that you don't even know.
Modeling a Basketball
Say we work for a basketball manufacturer and we want to simulate production of basketballs for quality assurance purposes. Now, a real basketball might have a lot of attributes - a color, a rubbery smell, fingerprints, air pressure, and so on. For our simple software model of a basketball, we choose to worry only about two attributes:
- What is the basketball's diameter?
- Is the basketball inflated or not?
Basketball
that has these two
attributes, along with some operations, or methods, for examining
or updating them.
Let's start by looking at how one of these Basketball
objects might be used, and then we'll look carefully at the code.