10.12.2012 Views

The Java Language Specification, Third Edition

The Java Language Specification, Third Edition

The Java Language Specification, Third Edition

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

8.8.10 Preventing Instantiation of a Class CLASSES<br />

248<br />

package p2;<br />

class SonOfOuter extends p1.Outer {<br />

void foo() {<br />

new Inner(); // compile-time access error<br />

}<br />

}<br />

<strong>The</strong> constructor for Inner is protected. However, the constructor is protected relative<br />

to Inner, while Inner is protected relative to Outer. So, Inner is accessible<br />

in SonOfOuter, since it is a subclass of Outer. Inner’s constructor is not accessible<br />

in SonOfOuter, because the class SonOfOuter is not a subclass of Inner!<br />

Hence, even though Inner is accessible, its default constructor is not.<br />

8.8.10 Preventing Instantiation of a Class<br />

A class can be designed to prevent code outside the class declaration from creating<br />

instances of the class by declaring at least one constructor, to prevent the creation<br />

of an implicit constructor, and declaring all constructors to be private. A<br />

public class can likewise prevent the creation of instances outside its package by<br />

declaring at least one constructor, to prevent creation of a default constructor with<br />

public access, and declaring no constructor that is public.<br />

Thus, in the example:<br />

class ClassOnly {<br />

private ClassOnly() { }<br />

static String just = "only the lonely";<br />

}<br />

the class ClassOnly cannot be instantiated, while in the example:<br />

package just;<br />

public class PackageOnly {<br />

PackageOnly() { }<br />

String[] justDesserts = { "cheesecake", "ice cream" };<br />

}<br />

the class PackageOnly can be instantiated only within the package just, in<br />

which it is declared.<br />

DRAFT

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!