Simple way to understand Encapsulation and Abstraction

后端 未结 15 1127
谎友^
谎友^ 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:31

    Well I will explain abstraction with a real world example. Say in your house you do have an electric plug and many devices can connect to the same plug but plug will never have an idea which device it is connected to, in other words the details of the devices is abstracted (hidden) to the plug.

    Think what if we connect a device directly to electric wire without a plug? Say connect a bulb directly to a wire, then wire knows which device it is connected to and when ever we need to replace the bulb then we have to remove the wire connection from the bulb, which means bulb is tightly coupled with the wire. In other words bulb and wire knows the details where it is connected to, means not abstracted.

    In object oriented world abstraction works exactly same. The class which consume other classes function/property doesn't need to know which classes function/property it is consuming and everything should be abstracted with an interface / abstract class.

    Let me code the same example. Here I have a class "ElectricPlug", which is running a device. But the class "ElectricPlug" doesn't have any idea which device it is running. It can be any class implementing the interface "IDevice", which means the implementation of "RunDevice" is abstracted from "ElectricPlug". Here is the full sample code,

    class Program
    {
        static void Main(string[] args)
        {
            ElectricPlug electricPlug = new ElectricPlug(new Bulb());
        }
    }
    
    public class ElectricPlug
    {
        private readonly IDevice _device;
        public ElectricPlug(IDevice device)
        {
            _device = device;
        }
    
        public void Run()
        {
            _device.Rundevice();
        }
    }
    
    
    public interface IDevice
    {
        void Rundevice();
    }
    
    
    public class Bulb : IDevice
    {
        public void Rundevice()
        {
           Console.WriteLine("Switched on bulb");
        }
    }
    
    0 讨论(0)
  • 2020-11-27 10:33

    Abstraction is a means of hiding details in order to simplify an interface.

    So, using a car as an example, all of the controls in a car are abstractions. This allows you to operate a vehicle without understanding the underlying details of the steering, acceleration, or deceleration systems.

    A good abstraction is one that standardizes an interface broadly, across multiple instances of a similar problem. A great abstraction can change an industry.

    The modern steering wheel, brake pedal, and gas pedal are all examples of great abstractions. Car steering initially looked more like bicycle steering. And both brakes and throttles were operated by hand. But the abstractions we use today were so powerful, they swept the industry.

    --

    Encapsulation is a means of hiding details in order to protect them from outside manipulation.

    Encapsulation is what prevents the driver from manipulating the way the car drives — from the stiffness of the steering, suspension, and braking, to the characteristics of the throttle, and transmission. Most cars do not provide interfaces for changing any of these things. This encapsulation ensures that the vehicle will operate as the manufacturer intended.

    Some cars offer a small number of driving modes — like luxury, sport, and economy — which allow the driver to change several of these attributes together at once. By providing driving modes, the manufacturer is allowing the driver some control over the experience while preventing them from selecting a combination of attributes that would render the vehicle less enjoyable or unsafe. In this way, the manufacturer is hiding the details to prevent unsafe manipulations. This is encapsulation.

    0 讨论(0)
  • 2020-11-27 10:34

    Data Abstraction: DA is simply filtering the concrete item. By the class we can achieve the pure abstraction, because before creating the class we can think only about concerned information about the class.

    Encapsulation: It is a mechanism, by which we protect our data from outside.

    0 讨论(0)
  • 2020-11-27 10:36

    Abstraction is a process where you show only “relevant” data and “hide” unnecessary details of an object from the user. Consider your mobile phone, you just need to know what buttons are to be pressed to send a message or make a call, What happens when you press a button, how your messages are sent, how your calls are connected is all abstracted away from the user.

    Encapsulation is the process of combining data and functions into a single unit called class. In Encapsulation, the data is not accessed directly; it is accessed through the functions present inside the class. In simpler words, attributes of the class are kept private and public getter and setter methods are provided to manipulate these attributes. Thus, encapsulation makes the concept of data hiding possible.

    enter image description here

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-27 10:38

    Abstraction is like using a computer.

    You have absolutely no idea what's going on with it beyond what you see with the GUI (graphical user interface) and external hardware (e.g. screen). All those pretty colors and such. You're only presented the details relevant to you as a generic consumer.

    Encapsulation is the actual act of hiding the irrelevant details.

    You use your computer, but you don't see what its CPU (central processing unit) looks like (unless you try to break into it). It's hidden (or encapsulated) behind all that chrome and plastic.

    In the context of OOP (object-oriented programming) languages, you usually have this kind of setup:

    CLASS {
      METHOD { 
        *the actual code*
      }
    }
    

    An example of "encapsulation" would be having a METHOD that the regular user can't see (private). "Abstraction" is the regular user using the METHOD that they can (public) in order to use the private one.

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