java 17:数据域封装

来源:互联网 发布:淘宝助理首页怎么改 编辑:程序博客网 时间:2024/06/05 18:01

在我们上一篇用的例子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是不是还是正数的,但是如果我们能够用一个统一的函数对r进行设置时候,外界要对她进行赋值时候,必须调用这个函数,我们可以在我们的函数中做好检查的工作,这样我们就不用担心是不是在什么地方被改成不合适的数字了。

那么我们怎么防止外界对我们的数据域进行随意的修改呢?那么就是将数据域用private修饰,这样在对象之外就不能直接访问我们的数据域了。那么外界要进行设置或者读取怎么办?那我们就定义相应的get跟set函数,并且修饰为public。这样外界就只能通过我们统一的函数对数据域进行访问了。

To prevent direct modifications of data fields, you should declare the data fields private,
using the private modifier. This is known as data field encapsulation.
A private data field cannot be accessed by an object from outside the class that defines the
private field. But often a client needs to retrieve and modify a data field. To make a private

get函数是这么定义的

public returnType getPropertyName();

如果returnType是Boolean类型,那么get的函数为了可读性更强默认为 public returnType isPropertyName();

set 函数定义为 public void setPropertyName(dataType newValue);

所以现在改造我们的CircleCount;

class CircleCount{private double r=1.0;private static int count=0;CircleCount(){CircleCount.count++;}CircleCount(double r){this.r=r;CircleCount.count++;}public double getR(){return this.r;}public void setR(double r){this.r=(r>0?r:0);}public static int getCount(){return count;}public double getArea(){return r*r*Math.PI;}}public class TestCount{public static void main(String [] args){CircleCount C1=new CircleCount();C1.setR(3);System.out.println("c1.r="+C1.getR()+",c1.count="+C1.getCount());CircleCount C2=new CircleCount(5);C2.setR(-9);System.out.println("r="+C2.getR()+",count="+C2.getCount());}}

这样,因为count及r都是private,我们在类外的TestCount不能直接访问到这两个数据域,只能通过get,set函数来,在set中我们又可以对外界传入的值先做一个判断,这样也方便了我们对数据的维护。




0 0
原创粉丝点击