Java Access Specifiers


Each field and method in a class definition has an access level.Keywords private, protected andpublic are used to declare a field and / or method as private, protected and public, respectively. For package level access no modifies is used i.e. if we use no access modifier / specifier, itdefaults to package level access. The following table summarizes different access specifiers / modifiers available in Java programming langauage:

private
accessible only in this class
( no modifier )
accessible only in this package
protected
accessible only in this package and in all subclasses of this class
public
accessible everywhere this class is available

Similarly a class may be declared with the modifier public, in which case the class becomes visible to all classes, everywhere. On the contrary if a class has no modifier (the default, a.k.a. package-private) it becomes visible only within its own package.

For both fields and classes, package access is the default, and is used when no access modifier is specified. Java packages are discussed in the next lesson.

As discussed earlier, access control must be specified for every field and every method; there is no grouping as in C++. For example consider the following piece of code:

public
int x;
int y;

In the above piece of code only x is public; y gets the default, package access.

Static Fields and Methods
Fields and methods can also be declared static. If a field is declared as static, there is only one copy of the field for the entire class, rather than one copy for each instance of the class. A method that is declared as static cannot access any of the non-static fields of the class, and also it cannot call any non-static method. Methods that would be "free" functions in C++ i.e. not members of a class, should be static methods in Java. A public static field or method can be accessed from outside the class, with or without creating an instance of the class.

Final Fields and Methods
Fields and methods can also be declared final. A final method cannot be overridden in a subclass. A final field is like a constant: once it has been given a value, it cannot be assigned to again.