A visibility modifier affects which classes/programs can use a Method or Attribute. It is a crucial part of the Information Hiding paradigm, as it helps prevent unwanted access/changes to data.
Generally, Procedural Programming Languages such as C don’t use visibility modifiers, but instead use Program Scope to check where a function/variable can be accessed.
Java
The 3 key visibility modifiers in Java are:
public
: Keyword when applied to a class, method or attribute makes it available/visible everywhere (within the class and outside the class). Essentially makes it global.private
: Keyword when applied to a method or attribute of a class, makes them only visible within that class. Private methods and attributes are not visible within subclasses, and are not inherited.protected
: Keyword when applied to a method or attribute of a class, makes them only visible within that class, subclasses and also within all classes that are in the same package as that class. They are also visible to subclasses in other packages.
Java also has a default
visibility modifier, which is used when no other keywords are provided. A table of all the modifiers:
Modifier | Same Class | Same Package | Is a subclass | Other |
---|---|---|---|---|
public | Y | Y | Y | Y |
protected | Y | Y | Y | N |
default | Y | Y | N | N |
private | Y | N | N | N |
For example, a class with the a protected method can have other subclasses call the method, but any class that’s not in the same package and isn’t a subclass can’t access the method. |