[ Team LiB ] Previous Section Next Section

Chapter 2. Objects, Classes, and Interfaces

This chapter contains examples that illustrate the object-oriented nature of Java and show you how to define and use classes and interfaces. It is designed to be read in conjunction with Chapter 3 of Java in a Nutshell, which offers a complete introduction to the object-oriented concepts and syntax you must understand to program in Java. As a refresher, the following paragraphs summarize Java's object-oriented terminology.

An object is a collection of data values, or fields, plus methods that operate on that data. The data type of an object is called a class; an object is often referred to as an instance of its class. The class defines the type of each field in an object, and it provides the methods that operate on data contained in an instance of the class. An object is created using the new operator, which invokes a constructor of the class to initialize the new object. The fields and methods of an object are accessed and invoked using the . operator.

Methods that operate on the fields of an object are known as instance methods. They are different from the static, or class, methods that we saw in Chapter 1. Class methods are declared static; they operate on the class itself, rather than on an individual instance of the class. Fields of a class may also be declared static, which makes them class fields instead of instance fields. While each object has its own copy of each instance field, there is only one copy of a class field and it is shared by all instances of the class.

The fields and methods of a class may have different visibility levels, including public, private, and protected. These different levels of visibility allow fields and methods to be used in different contexts. Every class has a superclass, from which it inherits fields and methods. When a class inherits from another class, it is called a subclass of that class. Classes in Java form a class hierarchy. The java.lang.Object class is root of this hierarchy; Object is the ultimate superclass of all other classes in Java.

An interface is a Java construct that defines methods, like a class, but doesn't provide any implementations for those methods. A class can implement an interface by defining an appropriate implementation for each method in the interface.

    [ Team LiB ] Previous Section Next Section