java 17:数据域封装

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在我们上一篇用的例子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中我们又可以对外界传入的值先做一个判断,这样也方便了我们对数据的维护。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值