Access Control

Java's access specifiers are public, private, protected and a default access level.

A public class member can be accessed by any other code. A private class member can only be accessed within its class.

Default (without an access modifier)

A class's fields, methods and the class itself may be default. A class's default features are accessible to any class in the same package.

A default method may be overridden by any subclass that is in the same package as the superclass.

protected features are more accessible than default features. Only variables and methods may be declared protected.

A protected feature of a class is available to all classes in the same package(like a default). A protected feature of a class can be available to its subclasses.

Here is an example for a public member variable


public int i;

The following code defines a private member variable and a private member method:


private double j; 
private int myMethod(int a, char b) { // ...

To understand the effects of public and private access, consider the following program:

 
class Test {
  int a;        // default access
  public int b; // public access
  private int c; // private access
  // methods to access c
  void setc(int i) {
    c = i;
  }
  int getc() {
    return c;
  }
}
public class Main {
  public static void main(String args[]) {
    Test ob = new Test();
    ob.a = 1;
    ob.b = 2;
    // This is not OK and will cause an error
    // ob.c = 100; // Error!
    // You must access c through its methods
    ob.setc(100); // OK
    System.out.println("a, b, and c: " + ob.a + " " + ob.b + " " + ob.getc());
  }
}

The output:


a, b, and c: 1 2 100
Home 
  Java Book 
    Class  

Access Control:
  1. Access Control
  2. Member Access and Inheritance
  3. Class Member Access Protection and Package
  4. Modifiers and Features