Dart Abstract classes

In this tutorial you will learn about the Dart Abstract classes and its application with practical example.

Dart Abstract Classes

Any class that contains one or more abstract methods is known as abstract class. A class can be declared abstract using the “abstract” keyword followed by class declaration. A class declared abstract may or may not include abstract methods. An abstract class can have abstract methods(methods without implementation) as well as concrete methods (methods with implementation). A normal class(non abstract class) is not allowed to have abstract methods.

An abstract class can not be instantiated, which means you are not allowed to create an object of it. Abstract classes can only be extended; and the subclass must provide implementations for all of the abstract methods in its parent class. If a subclass does not implements abstract methods, then the subclass must also be declared abstract.

Note :- An abstract method is a method that is declared without an implementation.

Rules for Abstract Classes

1.) Abstract classes may or may not include abstract methods (methods without body).
2.) If a class has at least one abstract method, then the class must be declared abstract.
3.) An abstract class can not be instantiated, but can be extended .
4.) If you inherit an abstract class, you have to provide implementations to all the abstract methods in it.
5.) An abstract class can be declared using abstract keyword.
6.) An abstract class may also have concrete (methods with body) methods.

Declaring Abstract Class

An abstract class can be defined using abstract keyword followed be class declaration. An abstract class is mostly used to provide a base for subclasses to extend and implement the abstract methods.

Recommended:-  Dart if else if Statement

Syntax:-

Usage Of Abstract Class

Lets say we have a class Employee that has a method showEmpInfo() and we have two subclasses of it Manager and Engineer. Since the each of the employee information differs from other employee, then there is no point to implement showEmpInfo() method in parent class. This is because every subclass must override this method to give its own implementation. Thus, making this method abstract would be the good choice as by making this method abstract we force all the sub classes to implement this method, also we need not to give any implementation to this method in parent class.

Example:-

Now, when we run above Dart Program, we will see following output.

Recommended:-  Dart Typedef

Output:-

dart_method_overriding_example

In this tutorial we have learn about the Dart Abstract classes and its application with practical example. I hope you will like this tutorial.