public is a Java keyword which declares a member's access as public. Public members are visible to all other classes. This means that any other class can access a
public field or method. Further, other classes can modify
public fields unless the field is declared as
A best practice is to give fields
private access and reserve
public access to only the set of methods and
final fields that define the class' public constants. This helps with encapsulation and information hiding, since it allows you to change the implementation of a class without affecting the consumers who use only the public API of the class.
Below is an example of an immutable
public class named
Length which maintains
private instance fields named
magnitude but provides a
public constructor and two
public accessor methods.
|Code listing: Length.java