一个OOP的最重要的方面就是数据隐藏。有人能解释用一段简单的代码数据隐藏的究竟是什么,以及为什么我们需要它?
One of the most important aspects of OOP is data hiding. Can somebody explain using a simple piece of code what data hiding is exactly and why we need it?
推荐答案我猜通过的数据隐藏的你的意思是这样的封装或具有物中的变量,只有获得和修改方法揭露它,通常当你想执行一些逻辑做设置一个价值?
I'm guessing by data hiding you mean something like encapsulation or having a variable within an object and only exposing it by get and modify methods, usually when you want to enforce some logic to do with setting a value?
public class Customer { private decimal _accountBalance; public decimal GetBalance() { return _accountBalance; } public void AddCharge(decimal charge) { _accountBalance += charge; if (_accountBalance < 0) { throw new ArgumentException( "The charge cannot put the customer in credit"); } } }
即。在这个例子中,我让消费类来获取客户的平衡,但我不会让他们直接设置它。不过,我已经暴露的方法,让我通过通过在充电增加它 AddCharge $修改 _accountBalance 类的实例中C $ C>方法。
I.e. in this example, I'm allowing the consuming class to get the balance of the Customer, but I'm not allowing them to set it directly. However I've exposed a method that allows me to modify the _accountBalance within the class instance by adding to it via a charge in an AddCharge method.
下面是一个的文章,你可能会发现有用的。
Here's an article you may find useful.
更多推荐
什么是数据隐藏的含义
发布评论