what is the meaning of data hiding

后端 未结 7 1996
小鲜肉
小鲜肉 2021-01-19 03:23

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?

7条回答
  •  感动是毒
    2021-01-19 04:02

    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");
            }
        }    
    }
    

    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.

提交回复
热议问题