2

I have gone through lots of posts but did not get the point.

Can we say : abstraction = encapsulation + data hiding

Or it is more than that!!

Thanks

  • 2
    One has nothing to do with the other. Your question is off-topic too –  Jan 20 '18 at 03:58
  • Have you read [What does abstraction mean in programming?](https://stackoverflow.com/q/21220155/3744182) and [Simple way to understand Encapsulation and Abstraction](https://stackoverflow.com/q/16014290) and [Encapsulation vs Abstraction?](https://stackoverflow.com/q/8960918) ? Do those address your question? – dbc Jan 20 '18 at 04:23
  • The following reading will clear all your doubts: [Abstraction, Encapsulation, and Information Hiding](http://www.tonymarston.co.uk/php-mysql/abstraction.txt) – Edwin Dalorzo Jan 21 '18 at 12:29

1 Answers1

2

This question is more of an object oriented question. #oop would be a good tag to include here.

To answer your question: No, abstraction does not equal encapsulation and data hiding. By the way abstraction and encapsulation both have data hiding concepts. However, they are not the same.

Encapsulation is about hiding variables or methods within a class to prevent any changes from the outside world. Then we can control what is being manipulated through getter/setter methods. Brief example is when we have a Person class. In this Person class let's assume we have a variable to keep track of age. Now, we have a GetAge() method to return the age of the Person; on the other hand, we have modified the SetAge(int age) method to only set the new age if the passed in argument is a greater age than the current age (because we only get older as time goes by...).

public class Person {

    private int age;

    public Person(int age) { 
        this.age = age; 
    }

    public int GetAge() { 
        return age 
    }

    public void SetAge(int age) {
        if (this.age < age) { 
            this.age = age; 
        }
    }
}

Abstraction is used to extract and highlight the main functionality that will be shared for a generic abstract class or interface. Brief example is when we have an interface for an IAnimal. In this interface we just create a template for methods of Eat(int numOfBowls) and Sleep(double hours). We have abstracted out the necessary methods for any animal (this is abstraction). The code below will clearly show you what I mean, but I also gave an example of using Inheritance which is the other main concept of Objected-Oriented Programming (this will not be covered here since it's out of scope from the question at hand).

public interface IAnimal {
    void Eat(int numOfBowls);
    void Sleep(double hours);
}

public class Dog : IAnimal {

    public void Eat(int numOfBowls) {
        // eat numOfBowls passed in
    }

    public void Sleep(double hours) {
        // sleep for number of hours passed in
    }

    public void Bark() { 
        Console.WriteLine("woof");
    }
}
Bae
  • 88
  • 6