Skip to Content
Think Java
book

Think Java

by Allen B. Downey, Chris Mayfield
May 2016
Beginner content levelBeginner
249 pages
5h 13m
English
O'Reilly Media, Inc.
Content preview from Think Java

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learn Java the Easy Way

Learn Java the Easy Way

Bryson Payne
Optimizing Java

Optimizing Java

Benjamin J. Evans, James Gough, Chris Newland

Publisher Resources

ISBN: 9781491929551Errata Page