9.2. Fields and Methods

The Java language provides four access modes, which should be used properly: public, protected, private, and package private, which is the default if no mode is explicitly specified. A common example of improper use is the inexperienced programmer who, when writing a time zone class, mistakenly declares fields or variables that are publicly accessible:

public TimeZone defaultZone;

This design has a number of problems. First, any person or code, including untrusted code, can access this field and directly change the value of the default time zone. Second, because multiple threads can access this field, some synchronization is needed. Following is a better design:

 private TimeZone defaultZone = null; public synchronized ...

Get Inside Java™ 2 Platform Security: Architecture, API Design, and Implementation, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.