Chapter 3. Object-Oriented Programming in Java

Now that we’ve covered fundamental Java syntax, we are ready to begin object-oriented programming in Java. All Java programs use objects, and the type of an object is defined by its class or interface. Every Java program is defined as a class, and nontrivial programs usually include a number of classes and interface definitions. This chapter explains how to define new classes and interfaces and how to do object-oriented programming with them.[1]

This is a relatively long and detailed chapter, so we begin with an overview and some definitions. A class is a collection of fields that hold values and methods that operate on those values. Classes are the most fundamental structural element of all Java programs. You cannot write Java code without defining a class. All Java statements appear within methods, and all methods are implemented within classes.

A class defines a new reference type, such as the Point type defined in Chapter 2. An object is an instance of a class. The Point class defines a type that is the set of all possible two-dimensional points. A Point object is a value of that type: it represents a single two-dimensional point.

Objects are usually created by instantiating a class with the new keyword and a constructor invocation, as shown here:

Point p = new Point(1.0, 2.0);

Constructors are covered in Section 3.3 later in this chapter.

A class definition consists of a signature and a body . The class signature defines the ...

Get Java in a Nutshell, 5th Edition 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.