java 17:数据域封装

本文讨论了在Java中数据域封装的重要性,指出直接修改数据域可能导致数据篡改和维护困难。为了解决这些问题,建议将数据字段声明为private,并通过getter和setter方法提供访问。通过封装,可以确保对数据的正确操作,增强代码的健壮性和可维护性。
摘要由CSDN通过智能技术生成

在我们上一篇用的例子CircleCount中使用的r跟count,这两个数据域我们可以直接通过C.count=6, C.r=-10等这样类似的形式对其进行修改,这是非常不好的。因为:

■ First, data may be tampered with. For example, numberOfObjects is to count the
number of objects created, but it may be mistakenly set to an arbitrary value (e.g.,
Circle2.numberOfObjects = 10).
■ Second, the class becomes difficult to maintain and vulnerable to bugs. Suppose you
want to modify the Circle2 class to ensure that the radius is nonnegative after other
programs have already used the class. You have to change not only the Circle2
class but also the programs that use it, because the clients may have modified the
radius directly (e.g., myCircle.radius = -5)

也就是

1) 数据可能被恶意修改,例如我们count是用来计算创建的对象的个数,但现在我们可以直接修改它。

2)不利于我们维护及容易出现bug,因为像我们可能在外面直接令 C.r=-23等这样的负数,每次我们回去使用我们的对象时候,我们必须检查我们的r是不是还是正数的,但是如果我们能够

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值