Question on #java# : Why do we need get, set methods in properties

ling127128 注册会员
2023-02-28 01:06

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.


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.

cythere 注册会员
2023-02-28 01:06

Hope to adopt
This is object-oriented programming in Java
The get and set methods are used to access and modify properties, they can control the access and modification of properties, To ensure the security and validity of the attribute. The get method is used to get the value of the property, and the set method is used to set the value of the property.

dyfdyfdyf 注册会员
2023-02-28 01:06

Class member variables are defined as private types. If an outside party needs to access or modify these member variables, you need to provide the appropriate access interface. set and get are interface functions dedicated to member variable access

About the Author

Question Info

Publish Time
2023-02-28 01:06
Update Time
2023-02-28 01:06