Getters and Setters 3599 - Chuck Norris Cipher Encoder (Java)
Getters and Setters 3599 - Chuck Norris Cipher Encoder (Java)
In most cases, a class does not expose its fields to other classes. Instead, it
makes its fields accessible through so called accessor methods. In this topic, you
will learn what advantages this approach offers and how to use it properly.
1. Data encapsulation.
According to the data encapsulation principle, the fields of a class cannot be
directly accessed from other classes. The fields can be accessed only through the
methods of that particular class.
To access hidden fields, programmers write special types of methods: getters and
setters. Getters can only read fields, and setters can only write (modify) the
fields. Both types of methods should be public.
Using these methods gives us some advantages:
the fields of a class can be made read-only, write-only, or both;
a class can have total control over what values are stored in the fields;
users of a class don't know how the class stores its data and don't depend on the
fields.
3. Conclusion.
To restrict access to fields from external code, make them private and write
suitable getters/setters to read/change only the fields you need. Do not forget to
make use of the naming convention when writing them.
Note, modern IDEs (such as IntelliJ IDEA) can generate getters and setters
automatically based on class fields.