1. Visibility Modifiers
Visibility ("Access") Modifiers
Visibility modifiers, also known as access modifiers control whether other classes can use a field or execute a method.
Visibility modifiers can be applied on an entire type (class, interface, abstract class, etc), or they can be individually applied to fields and methods. There are four modifiers: public, private, protected
and no modifier. Having no modifier is sometimes called the "default modifier" or "package modifier". Top level types can only be public or default (not private or protected).
public class MyClass { //"public" being applied to whole class int x; //no modifier applied to x, this is called the "default modifier" private int y; //private being applied to y protected int z; //protected public int a; //public public void example1() { //public being applied to a method } }
Note that Java allows only one public class per file, and the filename must be equal to the class
Permissions
When the public modifier is applied, then any code can use the class, method, or field. When private is applied, only code within the same class can reference the field or method. Here is a full table of how the modifier affects code that is within the same class, within the same package (folder), within a subclass, or anywhere ("world"):
public |
Y | Y | Y | Y |
protected |
Y | Y | Y | N |
no modifier | Y | Y | N | N |
private |
Y | N | N | N |
Why use visibility modifiers?
Visibility modifiers are useful in organizing code, especially for others to use. When you create a class, you may want a set of fields to be only be modified through a series of methods. These methods could be made public such that other classes (potentially written by other programmers) can execute them. The set of publicly facing methods is often called a system's Application Programming Interface ("API"). However, it is important to note that marking a field as private does not guarantee it cannot be accessed to a determined user. Reflection and memory inspection can be used to inspect private fields, and so the visibility modifiers should not be relied upon for security purposes.