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.

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.

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?


Figure 1: One six sided die from a pair of dice

Can you modify the Die class to keep a record of all the values this dice has rolled? How would you do that?

Next Section - Inheritance