Simple way to understand Encapsulation and Abstraction

后端 未结 15 1211
谎友^
谎友^ 2020-11-27 09:47

Learning OOP concepts especially interested to understand Abstraction and Encapsulation in depth.

Checked out the below already

Abstraction VS Information Hi

15条回答
  •  天涯浪人
    2020-11-27 10:37

    An example using C#

    //abstraction - exposing only the relevant behavior
    public interface IMakeFire
    {
         void LightFire();
    }
    
    //encapsulation - hiding things that the rest of the world doesn't need to see
    public class Caveman: IMakeFire
    {
         //exposed information  
         public string Name {get;set;}
    
         // exposed but unchangeable information
         public byte Age {get; private set;}
    
         //internal i.e hidden object detail. This can be changed freely, the outside world
         // doesn't know about it
         private bool CanMakeFire()
         {  
             return Age >7;
         }
    
         //implementation of a relevant feature
         public void LightFire()
         {
            if (!CanMakeFire())
            {
               throw new UnableToLightFireException("Too young");
            }
            GatherWood();
            GetFireStone();
            //light the fire
    
         }
    
         private GatherWood() {};
         private GetFireStone();
    }
    
    public class PersonWithMatch:IMakeFire
    {
          //implementation
     }
    

    Any caveman can make a fire, because it implements the IMakeFire 'feature'. Having a group of fire makers (List) this means that both Caveman and PersonWithMatch are valid choises.

    This means that

      //this method (and class) isn't coupled to a Caveman or a PersonWithMatch
      // it can work with ANY object implementing IMakeFire
      public void FireStarter(IMakeFire starter)
      {
            starter.LightFire();
        }
    

    So you can have lots of implementors with plenty of details (properties) and behavior(methods), but in this scenario what matters is their ability to make fire. This is abstraction.

    Since making a fire requires some steps (GetWood etc), these are hidden from the view as they are an internal concern of the class. The caveman has many other public behaviors which can be called by the outside world. But some details will be always hidden because are related to internal working. They're private and exist only for the object, they are never exposed. This is encapsulation

提交回复
热议问题