Chapter 11. Designing Classes
Whenever you create a new class, you are creating a new object type with the same name. So way back in “The Hello World Program”, when we created the class
Hello, we also created an object type named
We didn’t declare any variables with type
Hello, and we didn’t use
new to create
Hello objects. And it wouldn’t have done much good if we had—but we could have!
In this chapter, you will learn to design classes that represent useful objects. Here are the main ideas:
Again, defining a class creates a new object type with the same name.
A class definition is a template for objects: it specifies what attributes the objects have and what methods can operate on them.
Every object belongs to an object type; that is, it is an instance of a class.
newoperator instantiates objects; that is, it creates new instances of a class.
Think of a class as a blueprint for a house: you can use the same blueprint to build any number of houses.
The Time Class
A common reason to define a new class is to encapsulate related data in an object that can be treated as a single unit. That way, we can use objects as parameters and return values, rather than passing and returning multiple values. You have already seen two types that encapsulate data in this way:
Another example, which we will implement ourselves, is
Time, which represents a time of day. The data encapsulated in a
Time object includes an hour, a minute, and a number of seconds. Because ...