,

Declaring Members: Fields and Methods – Basics of Java Programming

Declaring Members: Fields and Methods

Example 1.1 shows the declaration of the class Point2D depicted in Figure 1.1. Its intention is to illustrate the salient features of a class declaration in Java, rather than an industrial-strength implementation. We will come back to the nitty-gritty of the Java syntax in subsequent chapters.

In Example 1.1, the character sequence // in the code indicates the start of a single-line comment that can be used to document the code. All characters after this sequence and to the end of the line are ignored by the compiler.

A class declaration can contain member declarations that define the fields and the methods of the objects the class represents. In the case of the class Point2D, it has the following two fields declared at (1):

  • x, which is the x-coordinate of a point
  • y, which is the y-coordinate of a point

The class Point2D has five methods, declared at (3), that implement the essential operations provided by a point:

  • getX() returns the x-coordinate of the point.
  • getY() returns the y-coordinate of the point.
  • setX() sets the x-coordinate to the value passed to the method.
  • setY() sets the y-coordinate to the value passed to the method.
  • toString() returns a string with the coordinate values formatted as “(x,y)”.

The class declaration also has a method-like declaration at (2) with the same name as the class. Such declarations are called constructors. As we shall see, a constructor is executed when an object is created from the class. However, the implementation details in the example are not important for the present discussion.

Example 1.1 Basic Elements of a Class Declaration

Click here to view code image

// File: Point2D.java
public class Point2D {             // Class name
  // Class Member Declarations

  // Fields:                                                         (1)
  private int x;     // The x-coordinate
  private int y;     // The y-coordinate

  // Constructor:                                                    (2)
  public Point2D(int xCoord, int yCoord) {
    x = xCoord;
    y = yCoord;
  }
  // Methods:                                                        (3)
  public int  getX()           { return x; }
  public int  getY()           { return y; }
  public void setX(int xCoord) { x = xCoord; }
  public void setY(int yCoord) { y = yCoord; }
  public String toString() { return “(” + x + “,” + y + “)”; } // Format: (x,y)
}

Related Posts