Wednesday, March 09, 2005

Access Control


This is about access control. The access modifiers are:

  • private
  • package
  • protected
  • public

Concept: Try to be as restrictive as possible.

It is unusual to use access modifiers like public with the class containing the main method.

class JavaApplication { // normal code

public class JavaApplication { // unusual code


Access Control Table
Access Modifier Visible to its own class Visible to its own package Visible to subclasses Visible to any class (Universe)
Access Level private yes
"package" (default) yes yes (package)
protected yes yes yes
public yes yes yes yes

  • "package" (default, not a keyword) == default accessibility
  • Universe == World
  • modifier == specifier
  • member variables should generally be kept private
  • member variables declared static final should be public
  • set and get methods should be public

Top-level Classes

['public' | ? package ? ] class TopLevel {
  ['public' | 'protected' | ? package ? | 'private'] int i;

  ['public' | 'protected' | ? package ? | 'private'] class Inner {

A top-level class can only be declared public or "package". All other class members can be declared public, protected, "package", or private


Start with the most restrictive access level; private. If the program does not compile, then try a less restrictive access modifier; package, protected and finally public.

No comments: