Java Reference
In-Depth Information
• The methods move , getX , and getY of the class Point are declared public and so
are available to any code that uses an object of type Point .
• The fields x and y are declared protected and are accessible outside the pack-
age points only in subclasses of class Point , and only when they are fields of
objects that are being implemented by the code that is accessing them.
See § 6.6.2 for an example of how the protected access modifier limits access.
Example 6.6-2. Access to public Fields, Methods, and Constructors
A public class member or constructor is accessible throughout the package where it is
declared and from any other package, provided the package in which it is declared is
observable (§ 7.4.3 ) . For example, in the compilation unit:
package points;
public class Point {
int x, y;
public void move(int dx, int dy) {
x += dx; y += dy;
moves++;
}
public static int moves = 0;
}
the public class Point has as public members the move method and the moves field. These
public members are accessible to any other package that has access to package points .
The fields x and y are not public and therefore are accessible only from within the pack-
age points .
Example 6.6-3. Access to public and Non- public Classes
If a class lacks the public modifier, access to the class declaration is limited to the pack-
age in which it is declared (§ 6.6 ). In the example:
Click here to view code image
package points;
public class Point {
public int x, y;
public void move(int dx, int dy) { x += dx; y += dy; }
}
class PointList {
Point next, prev;
}
Search WWH ::




Custom Search