Java Reference
In-Depth Information
Now that we've introduced all the major elements of a well-encapsulated class, it's
time to look at a proper syntax template for an entire class. Sun's Java style guide-
lines suggest putting fields at the top of the class, followed by constructors, followed
by methods:
public class <class name> {
// fields
private <type> <name>;
private <type> <name>;
...
// constructors
public <class name>(<type> <name>, ..., <type> <name>) {
<statement>;
<statement>;
...
<statement>;
}
...
// methods
public <type> <name>(<type> <name>, ..., <type> <name>) {
<statement>;
<statement>;
...
<statement>;
}
...
}
Here is the fourth complete version of our Point class, including encapsulated
fields and accessor methods getX and getY :
1 // A Point object represents a pair of (x, y) coordinates.
2 // Fourth version: encapsulated.
3
4 public class Point {
5 private int x;
6 private int y;
7
8 // constructs a new point at the origin, (0, 0)
9 public Point() {
10
this (0, 0); // calls Point(int, int) constructor
11 }
12
13 // constructs a new point with the given (x, y) location
14 public Point( int x, int y) {
Search WWH ::




Custom Search