2

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");
    }

}
Umair
  • 33
  • 2
  • 1
    Add `Fish`, `Ape`, `Insect`, `Alien` classes. Now try to write some code that has to `move` any of them. – Mat Jun 21 '19 at 07:00
  • where you used abstraction? – Exteam Jun 21 '19 at 07:00
  • By using abstraction, we can separate the things that can be grouped into another type. Frequently changing properties and methods can be grouped to a separate type so that the main type need not undergo changes. This adds strength to the OOAD principle. > "Code should be open for Extension but closed for Modification" Simplifies the representation of the domain models. And it took a major part in android to transfer data between fragments by passing instance and use the interface method to callback. – Arul Jun 21 '19 at 07:10

2 Answers2

1

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?!

GhostCat
  • 137,827
  • 25
  • 176
  • 248
1

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.

Codor
  • 17,447
  • 9
  • 29
  • 56