Modifiers are flags that are set on different attributes, objects etc. within a program to control certain things like access and other functionality.
There are two types of modifiers;
- Access – modifiers are used to set the access level for classes, attributes, methods and constructors. What that means is it will set who/what and how it can be accessed. Note when I say who I am referring to an object, maybe a service etc.
- Non-access – modifiers that do not control aceess levels but provide other functionality to the code, more detail below.
Note – The below types of modifiers refer to the Java language specifically so your mileage may vary with other languages!
- Public – class is accessible by any other class
- Default – class only accessible by classes in the same package, used when you don’t specify a different modifier, i.e. default
Attributes, methods & constructors:
- Public – code is accessible to all classes
- Private – only accessible within the declared class
- Default – code only accessible in the same package
- Protected – accessible in the same package and subclasses
- Final – class cannot be inherited by other classes
- Abstract – class cannot be used to create objects. To access it must be inherited from another class
Attributes and methods:
- Final – attributed and methods cannot be overriden/modified
- Static – belong to the class rather than the object, means it is loaded up and accessible to the whole JVM
- Abstract – can only be used in an abstract class and can only be used on methods. Method does not have a body for example
abstract void runCode();– the body is provided by the subclass (which it inheritied from)
- Transient – attributes and methods are skipped when serializing the object contianing them
- Synchronized – methods can only be accessible by one thread at a time
- Volatile – an attribute is not cached thread-locally and is always read from the “main memory”
As you will have read there is many modifiers than can be utlisied and should be for that fact too! I have never come acroess the “Volatile” modifier at all in actual code but looking forward to the day I do!