thumbnail

Abstract Classes In Dart

Published on 29 March 2020
Last Updated on 29 March 2020

An abstract class is a class that can’t be instantiated, instead they are used for defining interfaces that are used by other classes. Abstract classes can only be extended. Abstract classes are useful for defining blue-prints for other classes to implement.

If a subclass extends from an abstract class then it must implementations for all the abstract methods defined in the parent abstract class. If a subclass does not implement all methods defined in the parent abstract class then the subclass must be declared abstract as well.

Syntax for abstract classes in Dart

abstract class ClassName{
  // abstract fields
  // abstract methods
  // etc.
}

What is an abstract method

A method defined without any implementations is called as abstract method.

Rules for defining an abstract class

  • If a class has one or more than one abstract methods then it is mandatory to declare the class as abstract class using the abstract keyword.
  • If an abstract class is extended by a subclass then it must provide all implementations for the abstract methods defined in the parent class.
  • An abstract class can not be instantiated, this means you can not create a new object from the abstract class.
  • An abstract class can only be extended.
  • An abstract class can also have methods with implementations, also known as concrete methods.

Program using abstract class in Dart

Given below is a program that demonstrates how to abstract classes in Dart:

// program to demonstrate use of abstract class in Dart

abstract class Dog {
  // define various instance variables and methods that abstract class Dog must have

  String name;

  // following methods must be implemented by the child class
  void bark();
  void eat();
  void sleep();
  void jump();
  void walk();

  // concrete method
  void hello() {
    print('${name} says hello');
  }
}

class Tommy extends Dog {
  String name = 'Tommy';

  void bark() {
    print('${name} is barking!');
  }

  void eat() {
    print('${name} is eating!');
  }

  void sleep() {
    print('${name} is sleeping!');
  }

  void jump() {
    print('${name} is jumping!');
  }

  void walk() {
    print('${name} is walking!');
  }
}

main(List<String> args) {
  var tommy = new Tommy();
  tommy.bark();
  tommy.eat();
  tommy.sleep();
  tommy.jump();
  tommy.walk();
  tommy.hello();
}

Above program produces following output:

Tommy is barking!
Tommy is eating!
Tommy is sleeping!
Tommy is jumping!
Tommy is walking!
Tommy says hello

Above program makes use of abstract class Dog which is extended by subclass Tommy. Now subclass tommy must implement all abstract methods defined in parent abstract class.