Jump to content

Java Programming/Keywords/public

From Wikibooks, open books for an open world

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 final.

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 units and magnitude but provides a public constructor and two public accessor methods.

Computer code Code listing: Length.java
package org.wikibooks.java;

public class Length {
   private double magnitude;
   private String units;

   public Length(double magnitude, String units) {
      if ((units == null) || (units.trim().length() == 0)) {
          throw new IllegalArgumentException("non-null, non-empty units required.");
      }

      this.magnitude = magnitude;
      this.units = units;
   }

   public double getMagnitude() {
      return this.magnitude;
   }

   public String getUnits() {
      return this.units;
   }
}