We used modifiers such as public and private previously as describing field and method. Modifiers are used to specify the access authority to field and method. Java checks whether it can access the fields and method when it’s accessing object’s field or calling a method. Modifiers such as private and public are used to specify who can access the method or field.
There are 4 types of access control modifiers.
- public
- Anything can access to field and method
- protected
- the class itself and its subclass can access to it
- none
- anything in the same package can access to it
- private
- only class itself can access to it. Anything else can’t.
For example, the following code defines private “name” field, public “version” field, and public “changeName()” method.
Suppose there is another class “Cafe” class that uses User class, and it accesses to two fields directly as shown below.
Since “version” is public, it is accessible in all classes. But name field is private, so only User class can access to it. If another class access to private field or method as above, it will result in compile error.