Java Programming/Keywords/public

From Wikibooks, open books for an open world
Jump to: navigation, search

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
  1. package org.wikibooks.java;
    
  2.  
    
  3. public class Length {
    
  4.    private double magnitude;
    
  5.    private String units;
    
  6.  
    
  7.    public Length(double magnitude, String units) {
    
  8.       if ((units == null) || (units.trim().length() == 0)) {
    
  9.           throw new IllegalArgumentException("non-null, non-empty units required.");
    
  10.       }
    
  11.  
    
  12.       this.magnitude = magnitude;
    
  13.       this.units = units;
    
  14.    }
    
  15.  
    
  16.    public double getMagnitude() {
    
  17.       return magnitude;
    
  18.    }
    
  19.  
    
  20.    public String getUnits() {
    
  21.       return units;
    
  22.    }
    
  23. }