class的 get、set修饰符
class 中的属性前标注了 get set 即被称为 **访问器属性**
。其他的都是**数据属性**
访问器属性
和数据属性
有一些区别,例如:
- 访问器属性可以让你在读取或修改对象的属性时执行一些验证、计算或日志记录等操作,而数据属性不能。
- **访问器属性可以让你直接操作对象的属性,而不需要调用方法**,这样可以使代码更简洁和清晰。
- 访问器属性可以让你实现一些伪属性,也就是说,你可以定义一个没有实际存储值的属性,而是通过 get 和 set 方法来动态地计算或返回值。
1 |
|
可以看到,使用访问器属性的类可以直接用<u>person.name</u>
来获取或设置名字,而使用数据属性的类需要用<u>person.getName()</u>
和<u>person.setName()</u>
来调用方法。这就是访问器属性和数据属性的一个区别。
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!