Visibility in Java

Describes variable and method visibility in the Java programming language. Includes an interactive example of Java inheritance in two different packages.

Prerequisites

Objectives

Purpose of Visibility

Visibility in Java

Java has four visibility modifiers (least visible to most visible): private, (default), protected, public

  (least visible)     (most visible)
  private (default) protected public
Can be accessed from the same class
Can be accessed from the same package  
Can be accessed from any child class    
Can be accessed from anywhere      

Demonstration

  1. Move your mouse pointer over a variable declaration and your browser will highlight in yellow the classes where that variable is visible.
  2. Move your mouse pointer over a method header and your browser will highlight in orange the variables that method can use.
package p1;
public class C1 {
    private   static int a;
              static int b;
    protected static int c;
    public    static int d;

    private   int w;
              int x;
    protected int y;
    public    int z;

    private   static void m1() {...}
              static void m2() {...}
    protected static void m3() {...}
    public    static void m4() {...}

    private   void m5() {...}
              void m6() {...}
    protected void m7() {...}
    public    void m8() {...}
}
public class C2 {
    private C1 obj = new C1();

    public void m() {
        // cannot access C1.a
        // can access C1.b, C1.c, C1.d

        // can access obj
        // cannot access obj.w
        // can access obj.x, obj.y, obj.z

        // cannot call C1.m1()
        // can call C1.m2(), C1.m3(), C1.m4()

        // cannot call obj.m5()
        // can call obj.m6(), obj.m7(), obj.m8()
    }
}
public class C3 extends C1 {
    public void m() {
        // cannot access a
        // can access b, c, d

        // cannot access w
        // can access x, y, z

        // cannot call m1()
        // can call m2(), m3(), m4()

        // cannot call m5()
        // can call m6(), m7(), m8()
    }
}
 
package p2;
public class C4 extends C1 {
    public void m() {
        // cannot access a, b
        // can access c, d

        // cannot access w, x
        // can access y, z

        // cannot call m1(), m2()
        // can call m3(), m4()

        // cannot call m5(), m6()
        // can call m7(), m8()
    }
}
public class C5 {
    private C1 obj = new C1();

    public void m() {
        // cannot access C1.a, C1.b, C1.c
        // can access C1.d

        // can access obj
        // cannot access obj.w, obj.x, obj.y
        // can access obj.z

        // cannot call C1.m1(), C1.m2(), C1.m3()
        // can call C1.m4()

        // cannot call obj.m5(), obj.m6(), obj.m7()
        // can call obj.m8()
    }
}