Why we use abstraction

Viewed 72

I know what abstraction is but i want to know what is the purpose of using it, if we have to implement all the functions why not just write them for example

interface Moveable{
     public void move();
}
class Human implements Moveable{
    public void move(){
          System.out.println("walk");
    }

 }

 //or just write (why use abstraction)

class Human{
    public void move(){
          System.out.println("walk");
    }

}
2 Answers

Helpful abstractions are used to gain control over complexity.

Without such helpful abstractions, the first 5 lines of your first class are easier to write. But in the real world, anything that is of value will grow over time. Users want additional features, bugs occur and need to be fixed, and so on.

And when you aren't prepared for the next 500 lines of code, in the next classes, then that code will quickly turn into a maintenance nightmare.

In other words: the real world is too complicated to be fully represented in code. Thus you have to anticipate the essential "patterns" that matter in your application, and find ways to express them in more concise way.

In your example, yeah, there is only one class that implements that interface. But what if you had 50 classes, or 100? Then your client code would have to know that Human, Cat, Dog, Snake, ... all these classes have a move() method. Is that really simpler than being able to check "does the class implement the interface Moveable?!

Abstraction is used for two reasons. First to support reasoning and communication; if the main aspect under consideration of a human is that he or she can walk, then an explicit view of something that moves is appropriate. Second to provide unification of different implementations. Suppose there is a second implementation as follow.

class Tiger implements Moveable{
    public void move(){
        System.out.println("stalk");
    }
}

The interface Moveable provides a unified way to access a common type. That being said, if there is only one implementation of an interface, the interface is technically not necessary, but might still provide clarity and scalability of the implementation.

Related