Java Reference
In-Depth Information
We saw earlier that a class definition must have an access attribute of
public
if it is to be accessible
from outside the package. The next diagram shows the situation where the classes, seeking access to the
members of a public class, are in different packages.
Class1
SubClass1
Class2
No
No
OK
int a;
public int b;
OK
No
No
OK
protected int c;
private int e;
No
Package3
Package2
Package1
Here access is more restricted. The only members of
Class1
that can be accessed from an ordinary
class,
Class2
, in another package are those specified as
public
. Keep in mind that the class,
Class1
,
must also have been defined with the attribute
public
. From a sub-class of
Class1
that is in another
package, the members of
Class1
, without an access attribute, cannot be reached, and neither can the
private
members - these can never be accessed externally under any circumstances.
Specifying Access Attributes
As you probably gathered from the diagrams that we just looked at, to specify an access attribute for a
class member, you just add the keyword to the beginning of the declaration. Here is the
Point
class
you saw earlier, but now with access attributes defined for its members:
Try It Out - Accessing the Point Class
Make the following changes to your
Point
class. If you save it in a new directory, do make sure
Line.java
is copied there as well. It will be useful later if they are in a directory with the name
Geometry
.
public class Point {
// Create a point from its coordinates
public Point(double xVal, double yVal) {
x = xVal;
y = yVal;
}
// Create a Point from an existing Point object
public Point(final Point aPoint) {
x = aPoint.x;
y = aPoint.y;
}