O'Reilly logo

Java in a Nutshell, 5th Edition by David Flanagan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Fields and Methods

A class can be viewed as a collection of data and code to operate on that data. The data is stored in fields, and the code is organized into methods. This section covers fields and methods, the two most important kinds of class members. Fields and methods come in two distinct types: class members (also known as static members) are associated with the class itself, while instance members are associated with individual instances of the class (i.e., with objects). This gives us four kinds of members:

  • Class fields

  • Class methods

  • Instance fields

  • Instance methods

The simple class definition for the class Circle, shown in Example 3-1, contains all four types of members.

Example 3-1. A simple class and its members

public class Circle {
  // A class field
  public static final double PI= 3.14159;     // A useful constant

  // A class method: just compute a value based on the arguments
  public static double radiansToDegrees(double rads) { 
    return rads * 180 / PI; 
  }

  // An instance field
  public double r;                  // The radius of the circle

  // Two instance methods: they operate on the instance fields of an object
  public double area() {            // Compute the area of the circle
    return PI * r * r; 
  }
  public double circumference() {   // Compute the circumference of the circle
    return 2 * PI * r; 
  }
}

The following sections explain all four kinds of members. First, however, we cover field declaration syntax. (Method declaration syntax is covered in Section 2.6 later in this chapter.)

Field Declaration Syntax ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required