Chapter 11. Classes

Whenever you define a new class, you also create a new type with the same name. So way back in “The Hello World Program”, when we defined the class Hello, we created a type named Hello. We didn’t declare any variables with type Hello, and we didn’t use new to create a Hello object. It wouldn’t have done much if we had—but we could have!

In this chapter, we will define classes that represent useful object types. We will also clarify the difference between classes and objects. Here are the most important ideas:

  • Defining a class creates a new object type with the same name.

  • Every object belongs to some object type; that is, it is an instance of some class.

  • A class definition is like a template for objects: it specifies what attributes the objects have and what methods can operate on them.

  • The new operator instantiates objects, that is, it creates new instances of a class.

  • Think of a class like a blueprint for a house: you can use the same blueprint to build any number of houses.

  • The methods that operate on an object type are defined in the class for that object.

The Time Class

One 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. This design principle is called data encapsulation.

We have already seen two types that encapsulate data in this way: Point and Rectangle. Another example, which ...

Get Think Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.