Java Variables

Java: Protection Type of Variables, Methods or Classes

There are four levels of protection for variables, methods and Classes in Java and are listed and described below:
Package Protection (DEFAULT)
  • Default, not an explicit form of protection.
  • Variables,Methods or Classes of this type are accessibley only to all other classes in the same package.
  • Even if another package is imported, its package protected variables, methods and classes are not accessible, they stay hidden.
Private
  • Means that your methods, variables are accessible only to other methods in the same class.
  • NOT used for classes.
  • Example:
    class Student_Record {
       private String Social_Security_Number;
       private float GPA;
       String Name;
    
       .....
    
    }
    
    In the above example the GPA and SS# are private to this class, but, the Name is accessible by classes of the same package.
Public
  • Such methods, variables and classes are accessible to other methods inside or outside the current class or package.
  • Declare by preceeding declaration with the word public.
Protected
  • Such methods and variables are accessible to all classes inside the same package but only to subclasses outside the package.
  • NOT used for classes.
  • Declare by preceeding declaration with the word protected.
  • Support ability of subclasses to modify the data in a parent class even when this parent class is in a different package. Yet, do not have to declare public and let any class touch the data.


Handy-Dandy Cross-Reference Table
Same Class Sub Class Same Package Class outside package
public X X X X
protected X X X (only subclasses)
private X
package protected (default) X X X