简体   繁体   中英

How is abstraction an advantage of OOP if it can also be done procedurally?

I am completely new to programming and don't understand why abstraction is an advantage of OOP. All sites mention abstraction as one of the key advantages of OOP but this can be achieved procedurally also.

If I write:

int add(int x, int y){
   return x + y;
}

int main() {
   int z = add(3,4);
}

Abstraction is used to hide background details or any unnecessary implementation about the data so that users only see the required information, so isn't this also abstraction as the user can use "add" without knowing how it works? Did I get the idea of abstraction wrong because this is basically the only definition I got about abstraction online? If not then why is it an "advantage" if you can achieve it without OOP?

Your question is not bad, but it is a bit naive. It's quite obvious that you're asking about topics quite ahead of you. Good thing you're curious though. I mean no offense.

Abstraction is not a binary thing that a language supports or not. Languages does more or less abstraction, but all languages are abstractions above assembly language. I like C a lot, but it's not good for abstractions.

Abstraction is a very broad thing. Your question is a bit like what the purpose of wind instruments is since a guitar "can produce sound". It's not at all intended to insinuate that this would be a stupid question. I'm only mentioning it to illustrate how broad the topic of abstraction is. Creating a simple function is basically a few molecules on the top of the iceberg.

Just to show a quick and VERY simple example:

class Shape {
public:
    virtual double area();
};

class Triangle : public Shape {
private:
    double base, height;

public:
    double area() { return base*height/2.0; }
};

class Square : public Shape {
private:
    double side;

public:
    double area() { return side*side; }
};

int main() {
    Shape shapes = new Shape[10];
    // Init code   
    for(int i=0; i<10; i++) {
        std::cout << "Area: " << shapes[i] << std::endl;
    }
}

That's a level of abstraction that would be extremely messy to achieve in C. And then, this is not even a very complex example. It's as basic as it goes when it comes to show OOP.

Excuse my C++ code. All I know from C++, I learned 20 years ago. So it's probably a bit old school. Maybe it doesn't even compile, but it's just to show the abstraction. And it's aimed towards someone who comes from C.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM