10 Mar 1996


A class, field variable, or method can be declared to be public. Public names can be used by client application programs. Names that are not public are known only to the methods of the class or of related classes.

The public features of a class become a contract between the programmer writing the class and the programmers using it. If the definition of public elements change, then existing applications may no longer run. Therefore, public elements need to be carefully designed.

On the other hand, fields that are not public can be changed at any time. They effect only other code in the class or in its close relatives. The dynamic nature of Java allows a class to be replaced in its library at any time, and the new version of the class is immediately used in all applications that are launched from that library. If only non-public elements were changed (and if no bug was introduced into the code) then the applications will continue to run normally.

One view of good object oriented programming holds that there should be no public field variables (except, perhaps, for a few global constants). This philosophy holds that changes to an object should only be made by calling public methods that the programmer of the class chooses to expose. Consider an example of the opposite philosophy:

Date {
public byte month;
public static byte max_month=12;
public byte day;
public static byte max_day=31;
public short year;

The Date class allows the user to set any integer value into the fields. Despite the declaration of maximum values, nothing prevents someone from coding

Date today;

The object "today" now contains an invalid date. A better use of object oriented programming requires that new values of objects be set through a method that can enforce rules and check values.

However, if a programmer is converting an existing C program to Java, then objects of a class with all public variable fields corresponds to what C calls a "struct".

Continue Back PCLT

Copyright 1996 PC Lube and Tune -- Java H. Gilbert

This document generated by SpHyDir, another fine product of PC Lube and Tune.