In object-oriented programming, an attribute is a data member that describes the characteristics of an object. In general, we want object property values that can be read and modified by external code. This requires the use of the property's get and set methods.The
Get method is used to read the property values of the object, and the set method is used to modify the property values of the object. If a property does not provide get and set methods, then the value of the property cannot be read and modified by external code, which limits the flexibility and extensibility of the object.
At the same time, the get and set methods allow you to perform additional operations while reading and modifying property values, such as data validation, calculating properties, and so on. These operations can be implemented in the get and set methods to improve code reuse and maintainability.
For example, if the attribute of a class is age, we might want to do some verification when setting the age, such as determining whether the age is legal. You can do this using the set method. In addition, we can implement some computational logic in the get method, such as calculating age based on birthday.
Therefore, using the get and set methods makes code more flexible, extensible, and easy to maintain, which is an important characteristic of object-oriented programming.