Abstract Classes in Dart Programming

Dart ProgrammingServer Side ProgrammingProgramming

Abstract classes in Dart are classes that contain one or more abstract methods.

Note: Abstract methods are those methods that don't have any implementation.

It should also be noted that a class in Dart can be declared abstract using the "abstract" keyword followed by the class declaration. A class that is declared using the abstract keyword may or may include abstract methods.

An abstract class is allowed to have both the abstract methods and concrete methods (methods with implementation). Though, on the contrary, a normal class (non-abstract class) cannot have abstract methods.

An abstract class is mainly used to provide a base for subclasses to extend and implement the abstract methods that are present in the abstract class.

Syntax

An abstract class is defined by writing the abstract keyword followed by the class declaration.

abstract class ClassName {
   // body of abstract class
}

Example

 Live Demo

abstract class Employee{
   void showEmployeeInformation();
}

class Teacher extends Employee{
   @override
   void showEmployeeInformation(){
      print("I'm a teacher");
   }
}

class Principal extends Employee{
   @override
   void showEmployeeInformation(){
      print("I'm the principal.");
   }
}

void main(){
   Teacher teacher = new Teacher();
   Principal principal = new Principal();
   teacher.showEmployeeInformation();
   principal.showEmployeeInformation();
}

In the above example, we have a class Employee that has a method showEmployeeInformation() and then there are two subclasses of it Teacher and Principal. Since it is quite obvious that each employee information will be different from every other employee, so there's no point of implementing the method in the superclass, and hence we keep is abstracted.

Output

I'm a teacher
I'm the principal.
raja
Published on 21-May-2021 12:12:28
Advertisements