Abstraction in Dart

Abstraction in Dart

To hide the unnecessary details of an implementation

A simple example of abstraction is the concept of a car. When you drive a car, there is the concept of accelerating, braking, and turning the wheel to switch directions.

The driver doesn't need to know how the car stops when he presses the brake, or how the car accelerates when she presses the gas pedal.

The driver only needs to know the most necessary details which are to press on the pedals or to turn the wheels.

This is a useful concept in programming and dart has a facility to support that.

The abstract class

In Dart, we can make an abstract class by using the abstract keyword when creating a class.

abstract class Entity {
  String name;
  void greet();
}
  • An abstract class does not have an implementation in its methods.
  • Abstract methods do not have a method body.
  • An abstract class cannot be instantiated.
  • The abstract class can have fields or members.
  • The abstract class can have non-abstract methods.

It is a skeleton of methods that a class must implement. Think of it like a binding contract of signatures. A class that implements an abstract class is a subclass while the abstract class is called a superclass.

A concrete class

To implement abstract class, we can use extends to create a subclass.

class Human extends Entity {
  @override
  void greet() {
    print("Hello I am Human!");
  };
}

Note: You must override an abstract method of an abstract class.

Abstraction in Action

Suppose we want a function that make an Entity greet us.

We can write something like this:

void greeter(Entity entity) {
  entity.greet();
}

If we pass in an instance of a Human which is a subclass of an Entity, it will greet us appropriately!

var aHuman = Human();
greeter(aHuman); // Hello I am Human!

The greeter function does not care about the implementation of the Human it only cares and knows that it is an Entity and therefore has a greet() method.

Did you find this article valuable?

Support Jet’s Blog by becoming a sponsor. Any amount is appreciated!