Java Reference
In-Depth Information
package p1;
public class Outer {
protected class Inner {}
}
package p2;
class SonOfOuter extends p1.Outer {
void foo() {
new Inner(); // compile-time access error
}
}
The constructor for
Inner
is
protected
. However, the constructor is
protected
relative to
Inner
, while
Inner
is
protected
relative to
Outer
. So,
Inner
is accessible in
SonOfOuter
, since
it is a subclass of
Outer
.
Inner
's constructor is not accessible in
SonOfOuter
, because the
class
SonOfOuter
is not a subclass of
Inner
! Hence, even though
Inner
is accessible, its
default constructor is not.
8.8.10. Preventing Instantiation of a Class
A class can be designed to prevent code outside the class declaration from creating in-
stances of the class by declaring at least one constructor, to prevent the creation of an im-
plicit constructor, and by declaring all constructors to be
private
.
A
public
class can likewise prevent the creation of instances outside its package by declaring
at least one constructor, to prevent creation of a default constructor with public access, and
by declaring no constructor that is
public
.
Example 8.8.10-1. Preventing Instantiation via Constructor Accessibility
class ClassOnly {
private ClassOnly() { }
static String just = "only the lonely";
}
Here, the class
ClassOnly
cannot be instantiated, while in the following code:
package just;
public class PackageOnly {
PackageOnly() { }
String[] justDesserts = { "cheesecake", "ice cream" };