Java Reference
In-Depth Information
As I said earlier, a class definition must have an access attribute of
public
if it is to be accessible from
outside the package that contains it.
Figure 5-11
shows the situation where the classes seeking access to the
members of a public class are in different packages.
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
for this to be the case. A class that is not defined as
public
cannot be accessed at all from a class in another package.
From a subclass 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 in the previous section, to specify an access attribute for a class
member, you just add the appropriate 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 is useful later if they are in a directory with the name
Geometry
.
import static java.lang.Math.sqrt;
public class Point {
// Create a point from its coordinates
public Point(double xVal, double yVal) {
x = xVal;
y = yVal;
}