Java Reference
In-Depth Information
S ELF C HECK
14. What is a common reason for defining package-visible instance fields?
15. If a class with a public constructor has package access, who can
construct objects of it?
C OMMON E RROR 10.4: Accidental Package Access
It is very easy to forget the private modifier for instance fields.
public class BankAccount
{
. . .
double balance; // Package access really intended?
}
Most likely, this was just an oversight. The programmer probably never intended
to grant access to this field to other classes in the same package. The compiler
won't complain, of course. Much later, some other programmer may take
advantage of the access privilege, either out of convenience or out of evil intent.
This is a serious problem, and you must get into the habit of scanning your field
declarations for missing private modifiers.
C OMMON E RROR 10.5: Making Inherited Methods Less
Accessible
If a superclass declares a method to be publicly accessible, you cannot override it
to be more private. For example,
public class BankAccount
{
public void withdraw(double amount) { . . . }
. . .
}
public class CheckingAccount extends BankAccount
{
private void withdraw(double amount) { . . . }
// ErrorÈŒsubclass method cannot be more private
463
464
Search WWH ::




Custom Search