This book is now obsolete Please use CSAwesome instead.
11.2. Objects and Classes¶
In object-oriented programming the programmer writes a class which defines what all objects of the class know and can do. You can think of the class as like a cookie cutter or factory that produces objects. All objects created by the same class have the same fields and methods. A field is something the object knows about itself and a method is a thing the object can do.
A class also has constructors which initialize the fields when the object is created. A class can also have a main method which can be used to test the class.
11.2.1. Person Class¶
What should we want to know about a person? What we want to know depends on what problem we are trying to solve. In one situation we might want to know the person’s name and phone number and email. We need ways to get and set the data (fields) so we create getters and setters.
Modify the code above to add more constructors. Also modify the main method to test the new constructors.
11.2.2. Die Class¶
What if you wanted to represent a die which has 6 sides and you can roll it? You might also want to keep track of the last value rolled. Does the following class have everything it needs?
Can you modify the
Die class to keep a record of all the values this dice has rolled? How would you do that?
11.2.3. Coin Class¶
What if you just wanted to simulate flipping a coin? What would you need the objects of the class to know and do? You
would want to flip the coin (set it randomly to heads or tails) and ask if the value is heads or tails. See the class
below for one way to do this. Notice the use of a constant for HEADS. Any field that is declared to be
static can’t be changed and so is a constant.
Modify the class to add a isTails method that returns true when the value is not heads.