What is the difference between abstraction and encapsulation?

Possible duplicate:
difference between abstraction and encapsulation?

What exactly is the difference between encapsulation and abstraction in Java? Any brief examples would also be appreciated.

+7
source share
4 answers

Abstraction and encapsulation are two great flavors that combine perfectly.

Encapsulation minimizes what you show the user of your code. This "user" may be the rest of your code, or someone who uses the code you posted.

There are some specific advantages to encapsulation:

  • The user of your code is independent of the parts of your program that may change. When you change your program, they don’t need to change their code.
  • You more precisely control how your code and status changes throughout your program. You need to process fewer scripts and have fewer unexpected issues to fix.

I don't know Java, but here is a small example of encapsulation in C #:

public class Giraffe { public Giraffe(int heightInFeet) { this.heightInFeet = heightInFeet; this.numberOfSpots = heightInFeet * 72; } public override string ToString() { return "Height: " + heightInFeet + " feet" + " Number of Spots: " + numberOfSpots; } private int heightInFeet; private int numberOfSpots; } 

Instead of exposing numberOfSpots it is encapsulated inside the class and displayed using the ToString method.

Abstraction uses extension points so that the selection is delayed to the other part from which the exact code is executed. This choice can be made elsewhere in your program, in another program, or dynamically at run time.

There are also strong advantages to abstraction:

  • When changing the code that implements abstraction, the user of abstraction should not change his code. Until the abstraction changes, users do not have to change their code.
  • When you write code that uses an abstraction, you can write code once, which will be reused for any new code that implements this abstraction. You can write less code to do more.

Significant abstraction in C # is IEnumerable . Lists, arrays, dictionaries, and any other type of collection class implement IEnumerable . The foreach structure and the entire LINQ library are based on this abstraction:

 public IEnumerable<int> GetSomeCollection() { // This could return any type of int collection. Here it returns an array return new int[] { 5, 12, 7, 14, 2, 3, 7, 99 }; } IEnumerable<int> someCollectionOfInts = GetSomeCollection(); IEnumerable<string> itemsLessThanFive = from i in someCollectionOfInts where i < 5 select i.ToString(); foreach(string item in itemsLessThanFive) { Console.WriteLine(item); } 

You can also easily write your own abstractions:

 public interface IAnimal { bool IsHealthy { get; } void Eat(IAnimal otherAnimal); } public class Lion : IAnimal { public Lion() { this.isHealthy = true; } public bool IsHealthy { get { return isHealthy; } } void Eat(IAnimal otherAnimal) { if(otherAnimal.IsHealthy && !(otherAnimal is SlimeMold)) { isHealthy = true; } else { isHealthy = false; } } private bool isHealthy; } IAnimal someAnimal = PullAnAnimalOutOfAWoodenCrate(); Console.WriteLine("The animal is healthy?: " + someAnimal.IsHealthy); 

You can use both together, as was the case with IAnimal and IsHealthy . IAnimal is an abstraction and has only a get accessor, not a set accessor on IsHealthy - this is encapsulation.

+8
source

These two concepts are completely different.

Abstraction is the practice of creating an abstract base class, and then expanding its functionality. An abstract class is something that does not exist in a particular subject; its sole purpose should be expanded. Think if you are writing classes to represent different kinds. All of your different species can extend the abstract class of animals, because they will all have common attributes as animals. However, you would never create an instance of the Animal object, because each animal that you see in the world is a squirrel or a dog or fish ... or some specific implementation of this base, an abstract class of animals.

Encapsulation is the practice of making your class variables private, and then allowing access to them from the get and set methods. The purpose of this is how to access your data and how to implement it. For example, if you have a variable that has a requirement, then each time it changes, it also increments the second variable by 1, then you must encapsulate this functionality; this way your code is more reliable because you do not need to remember to adhere to this rule every time you access the original variable.

If you need specific code examples, I would recommend just doing a search on Google, because there were many such examples. Here are two:

http://www.tutorialspoint.com/java/java_abstraction.htm http://www.tutorialspoint.com/java/java_encapsulation.htm

+6
source

Encapsulation is the protection of your member variables or methods from the outside world.

Abstraction is a way to implement a specific implementation. which implementation to use is unknown to the user.

+4
source

Encapsulation is part of abstraction. The concept of abstraction is the creation of an object to represent another object. As a rule, the original object is more complex than abstraction. Thus, abstraction is a representation, usually as an aid to memory, for terminology / communication, etc. Think of it this way: abstract art is something else. The steering wheel, gear and 2/3 pedals are an abstraction of how the car works.

Basically, an abstraction allows you to imagine something complex, with lots of details, as something much simpler. In my opinion, this is connected with a “piece” in cognitive science. We cannot keep complex things in our heads, so we simplify by abstraction, and then use abstraction. Design patterns are another great example. Instead of talking about the details, we can talk about the Command, State or Strategy template, etc.

Encapsulation is part of the formation / creation of abstraction. The smaller the interface of the object, the easier it is to abstract. You do not need to know how the engine and gearbox work in order to drive a car, you just need to understand their abstractions (gear change and accelerator). Engine parts and gearboxes are encapsulated (in the interface) to create an abstraction.

Encapsulation is necessary for abstraction because abstraction cannot cope with all the real details and complexity (otherwise it is not an abstraction). Thus, gear shifting is an incomplete representation (or model) of the gearbox, but it is complete enough for everyday use. Encapsulation can be thought of as "hiding details", which is necessary to create a simpler view.

It is also important to discuss the concept of “interface”. In most cases, the terms "interface" and "abstraction" in this case are less used interchangeably. An interface is part of a system with which a user interacts or interacts. The interface to the car is the steering wheel, shift gear and pedals, etc. Abstraction creates an interface. You are not dealing directly with the engine / gearbox; you are dealing with their respective interfaces.

Another reason for encapsulation is that we are dealing with an incomplete model / abstraction, we do not understand the full complexity of the original and cannot trust to deal with all variables (because we do not understand the complete model). This is important for decoupling because, without abstraction, the interacting components will know too much about each other. Think about it, because every car has a steering wheel, pedals and gear shifts, you can control any car, regardless of engine type, etc. In addition, the gearbox is abstracted from the engine. Otherwise, a special gearbox will be required for each custom engine.

Similarly, a class is an abstraction. A class represents some complex model, through its interface - public members of the class. This interface is created by encapsulation. The class is a simplified interface of its more complex implementation for its employees. You can also think of it as a “need to know." Class members do not need to know exactly how this works. Just as you do not need to know how the engine works to drive a car.

Encapsulation, interfaces, and abstraction play a crucial role in integration and communication, and therefore in the maintenance of your code. If you do not create good abstractions and do not violate the “need to know” principle, your code becomes confusing, fragile and a nightmare to change it, because there is no “buffering”. The concept of OO "say don't ask" is also related to this.

+3
source

All Articles