what is the meaning of data hiding

后端 未结 7 1829
小鲜肉
小鲜肉 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:26

    What is data hiding?

    Here's an example:

    public class Vehicle
    {
        private bool isEngineStarted;
    
        private void StartEngine()
        {
            // Code here.
            this.isEngineStarted = true;
        }
    
        public void GoToLocation(Location location)
        {
            if (!this.isEngineStarted)
            {
                this.StartEngine();
            }
    
            // Code here: move to a new location.
        }
    }
    

    As you see, the isEngineStarted field is private, ie. accessible from the class itself. In fact, when calling an object of type Vehicle, we do need to move the vehicle to a location, but don't need to know how this will be done. For example, it doesn't matter, for the caller object, if the engine is started or not: if it's not, it's to the Vehicle object to start it before moving to a location.

    Why do we need this?

    Mostly to make the code easier to read and to use. Classes may have dozens or hundreds of fields and properties that are used only by them. Exposing all those fields and properties to the outside world will be confusing.

    Another reason is that it is easier to control a state of a private field/property. For example, in the sample code above, imagine StartEngine is performing some tasks, then assigning true to this.isEngineStarted. If isEngineStarted is public, another class would be able to set it to true, without performing tasks made by StartEngine. In this case, the value of isEngineStarted will be unreliable.

    0 讨论(0)
提交回复
热议问题