java 打破封装_关于java:setter和getter方法是否打破了封装?

本文探讨了封装的概念,指出getter和setter不一定会破坏封装,关键在于合理的访问策略。通过Person类的例子说明,对于不可变属性如名字和社保号,只提供getter,而对于可变属性如年龄,则提供incrementAge()方法。对于可以任意更改的属性如salary,提供setSalary()方法是合理的。这样的设计允许有限度地检查和修改对象状态,但遵循一定的规则,维护了封装性。
摘要由CSDN通过智能技术生成

Having getters and setters does not in itself break encapsulation.

What does break encapsulation is having a getter and a setter for

every data member (every field, in java lingo). That is one step away

from making all data members public.

The point of encapsulation is not that you should not be able to know

or to change the object's state from outside the object, but that you

should have a reasonable policy for doing it.

Consider an example of a class Person. Let's say a person has a name,

a social security number, and an age. Let's say that we do not allow

people to ever change their names or social security numbers. However,

the person's age should be incremented by 1 every year. In this case,

you would provide a constructor that would initialize the name and the

SSN to the given values, and which would initialize the age to 0. You

would also provide a method incrementAge(), which would increase the

age by 1. You would also provide getters for all three. No setters are

required in this case.

In this design you allow the state of the object to be inspected from

outside the class, and you allow it to be changed from outside the

class. However, you do not allow the state to be changed arbitrarily.

There is a policy, which effectively states that the name and the SSN

cannot be changed at all, and that the age can be incremented by 1

year at a time.

Now let's say a person also has a salary. And people can change jobs

at will, which means their salary will also change. To model this

situation we have no other way but to provide a setSalary() method!

Allowing the salary to be changed at will is a perfectly reasonable

policy in this case.

By the way, in your example, I would give the class Fridge the

putCheese() and takeCheese() methods, instead of get_cheese() and

set_cheese(). Then you would still have encapsulation.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值