JMU
Accessibility and Visibility
With Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Accessibility/Visibility
Kinds of Accessibility/Visibility
Block Entity is accessible within a block of code
Subprogram Entity is accessible within a subprogram
Class/Private Entity is accessible by all entities within a class
Generalized/Protected Entity is accessible in its class and all extensions
Complete/Public Entity is accessible everywhere

There are other types of accessibility/visibility as well, some of which we will encounter later.

Notation
Accessibility/Visibility in Java
images/accessibility_java.gif
Example Declarations in Java
A Common (Unrelated) Confusion
A Common (Unrelated) Confusion (cont.)

An Example

javaexamples/oopbasics/StaticMethods1.java
        /**
 * A class that contains a static method that
 * (incorrectly) uses a non-static attribute
 */
public class StaticMethods1
{
    private String          error;



    /**
     * An example method
     *
     * What Happens and Why?
     */
    public static void main(String[] args)
    {
        error = "Too small!";

        System.out.println(error);
    }
}
        
Block Accessibility

An Example

javaexamples/oopbasics/BlockAccessibility1.java
        /**
 * A class that illustrates block accessibilty
 */
public class BlockAccessibility1
{

    /**
     * An example method
     *
     * What Happens and Why?
     */
    public void example()
    {
        int        a;

        a = 5;

        for (int b=0; b < 10; b++)
        {
            System.out.println(b);
        }

        System.out.println(a);
        System.out.println(b);
    }
}
        
Block Accessibility (cont.)

An Example

javaexamples/oopbasics/BlockAccessibility2.java
        /**
 * A class that illustrates block accessibilty
 */
public class BlockAccessibility2
{
    /**
     * An example method
     *
     * What Happens and Why?
     */
    public void example()
    {
        int        a;

        a = 5;
        if (a <= 5)
        {
            String  error;
            error = "Too small!";
        } 
        else
        {
            error = "Too big";
        }

        System.out.println(error);
    }
}
        
Block Accessibility (cont.)
Block Accessibility (cont.)

An Example

javaexamples/oopbasics/TryCatch.java (Fragment: v1)
               try
       {
          String          token;
          StringTokenizer st;

          token = "Default";          
          st    = new StringTokenizer(line);
          token = st.nextToken();

          System.out.println(token);          
       }
       catch (NoSuchElementException nsee)
       {
          System.out.println(token);         
 
          // Compile-Time Error:
          //
          // cannot find symbol
       }
        
Block Accessibility (cont.)

A Similar Example

javaexamples/oopbasics/TryCatch.java (Fragment: v2)
               String          token;

       try
       {
          StringTokenizer st;

          token = "Default";          
          st    = new StringTokenizer(line);
          token = st.nextToken();

          System.out.println(token);          
       }
       catch (NoSuchElementException nsee)
       {
          System.out.println(token);          
 
          // Compile-Time Error:
          //
          // variable token might not have been initialized
       }
        
Subprogram Accessibility/Visibility

An Example

javaexamples/oopbasics/SubprogramAccessibility1.java
        /**
 * A class that illustrates subprogram accessibilty
 *
 * What Happens and Why?
 */
public class SubprogramAccessibility1
{

    public void buildMessage()
    {
        String         errorMessage;

        errorMessage = new String("It exploded!");
    }



    public void useMessage()
    {
        System.out.println(errorMessage);
    }
}
        
Subprogram Accessibility/Visibility (cont.)

A Common Mistake (Revisited)

/**
 * Explicit Value Constructor (for non-negative weights)
 *
 * @param pounds     The number of pounds (must be positive)
 * @param ounces     The number of ounces (must be positive)
 */
public Weight(int pounds, int ounces)
{
    Weight       aWeight;

    aWeight = new Weight(pounds, ounces, true);
}



/**
 * Explicit Value Constructor
 *
 * @param pounds     The number of pounds (must be positive)
 * @param ounces     The number of ounces (must be positive)
 * @param positive   true for a postive Weight, false for negative
 */
public Weight(int pounds, int ounces, boolean positive)
{
    this.pounds   = Math.abs(pounds);
    this.ounces = Math.abs(ounces);

    this.sign   = 1;
    if (!positive) this.sign = -1;
}
  
Private Accessibility

An Example

Suppose that the Signature class contains the following declaration:

private String email, name, saying, url;

What happens in the following application and why?

javaexamples/oopbasics/PrivateAccessibility1.java
        /**
 * An application that illustrates class/private accessibilty
 */
public class PrivateAccessibility1
{
    /**
     * The entry point of the application
     *
     * @param args   The command line arguments
     */
    public static void main(String[] args)
    {
        Signature         adamses, bernstdh;


        adamses = new Signature("Prof. Elizabeth Adams",
                                "adamses@jmu.edu",
                                "www.cs.jmu.edu/users/adamses/",
                                "The search for truth is more "+
                                "precious than its possession");

        bernstdh= new Signature("Prof. David Bernstein",
                                "bernstdh@jmu.edu",
                                "www.cs.jmu.edu/users/bernstdh/",
                                "Everything should be made as simple "+
                                "as possible, but not simpler.");

        bernstdh.saying = "I'm a little teapot, short and stout.";
    }
}
        
Private Accessibility (cont.)

An Example

javaexamples/oopbasics/Signature.java
        /**
 * An encapsulation of a signature at the end of
 * an email message
 *
 * @author  Somebody at James Madison University
 * @version 1.0
 */
public class Signature
{
    private String       email, name, saying, url;


    /**
     * Explicit Value Constructor
     */
    public Signature(String name, String email, String url,
                     String saying)
    {

        this.name    = name;
        this.email   = email;
        this.url     = url;
        this.saying  = saying;
    }


    /**
     * Compare the email address in this Signature
     * with the email address in another Signature
     *
     * @param other   The other Signature
     * @return        true if equal, false otherwise
     */
    public boolean hasSameEmailAddressAs(Signature other)
    {
        boolean       same;

        same = false;
        // Note that other.email is "visible"
        if (this.email.equals(other.email)) same = true;


        if (other.email.equals("bernstdh@jmu.edu")) 
        {
            other.saying = "I'm a little teapot, short and stout.";
        }

        return same;
    }


    /**
     * Get the String to append to the end of the 
     * email message
     *
     * @return   The String
     */
    public String toString()
    {
        String       s;

        s = "-----" + "\n" + 
            name + "\n" + email + ", " + url + "\n\n" +
            saying;

        return s;
    }
}
        
javaexamples/oopbasics/PrivateAccessibility2.java
        /**
 * An application that illustrates class/private accessibilty
 */
public class PrivateAccessibility2
{
    /**
     * The entry point of the application
     *
     * @param args   The command line arguments
     */
    public static void main(String[] args)
    {
        Signature         adamses, bernstdh;


        adamses = new Signature("Prof. Elizabeth Adams",
                                "adamses@jmu.edu",
                                "www.cs.jmu.edu/users/adamses/",
                                "The search for truth is more "+
                                "precious than its possession");

        bernstdh= new Signature("Prof. David Bernstein",
                                "bernstdh@jmu.edu",
                                "www.cs.jmu.edu/users/bernstdh/",
                                "Everything should be made as simple "+
                                "as possible, but not simpler.");

        if (adamses.hasSameEmailAddressAs(bernstdh)) 
        {
            System.out.println("They have the same email address.");
        } 
        else
        {
            System.out.println("They have different email address.");
        }

        System.out.println("\n\n");
        System.out.println(adamses.toString());

        System.out.println("\n\n");
        System.out.println(bernstdh.toString());
    }
}
        
Generalized/Protected Accessibility

An Example

javaexamples/oopbasics/im2/Chirp.java
        import java.util.*;

/**
 * A missive in an instant messaging system
 *
 * @author  Prof. David Bernstein
 * @version 2.0
 */
public class Chirp
{
    protected String          delimiters;  // Delimiters between words
    protected String          text;        // The text of the message

    /**
     * Explicit Value Constructor
     *
     * @param typed   What was typed by the user
     */
    public Chirp(String typed)
    {
        text       = typed;
        delimiters = " ,.;!?-\n\r";
    }

    /**
     * Get the number of words in this Chirp
     *
     * @return   The number of words
     */
    public int getNumberOfWords()
    {
        int                 numberOfWords;
        StringTokenizer     tokenizer;

        tokenizer     = new StringTokenizer(text, delimiters);
        numberOfWords = tokenizer.countTokens();

        return numberOfWords;
    }

    /**
     * Get the text of this Chirp
     *
     * @return   The text
     */
    protected String getText()
    {
        return text;
    }
}
        
javaexamples/oopbasics/im2/ExpandedChirp.java
        import java.io.*;
import java.util.*;

/**
 * A missive in an instant messaging system
 *
 * Unlike a normal Chirp, an ExpandedChirp does not
 * contain abbreviations -- they are all expanded
 *
 * @author  Prof. David Bernstein
 * @version 2.0
 */
public class ExpandedChirp extends Chirp
{
    private Properties      abbreviations;


    /**
     * Explicit Value Constructor
     *
     * @param typed   What was typed by the user
     */
    public ExpandedChirp(String typed)
    {
        super(typed);
        InputStream      is;

        abbreviations = new Properties();
        try 
        {
            is = new FileInputStream("abbreviations.txt");
            abbreviations.load(is);
        } 
        catch (IOException ioe)
        {
            // There was a problem opening the file
            // containing the abbreviations
        }
    }

    /**
     * Get the text of this Chirp with all of the
     * abbreviations expanded
     *
     * @return   The text
     */
    public String getText()
    {
        String       tempText;

        // Use the protected attribute in the parent
        tempText  = replaceAbbreviations(text);

        return tempText;
    }

    /**
     * Replace the abbreviations in a message
     *
     * @param msg   The original message
     */
    private String replaceAbbreviations(String msg)
    {
        String              replaced, token, word;
        StringTokenizer     tokenizer;

        replaced = "";
        
        // Use the protected attribute in the parent
        tokenizer = new StringTokenizer(msg, delimiters, true);
        while (tokenizer.hasMoreTokens())
        {
            token = tokenizer.nextToken();
            word  = abbreviations.getProperty(token);

            if (word == null) replaced += token;
            else              replaced += word;
        }

        return replaced;
    }
}
        
Generalized/Protected Accessibility (cont.)