Abstract method and abstract class in Dart

Abstract method and abstract class in Dart :

A class can be abstract or a method can be abstract in Dart. ‘abstract’ keyword is used to declare an Abstract class. An abstract can’t be instantiated or we can’t create any objects of abstract class. So, what is its use case ? You can only extend an abstract class.

Abstract methods are methods only with a declaration. We don’t have to write the method body. Use one semicolon (;) instead of the method body to make one method abstract.

Now, to link between abstract class and abstract methods in dart, we need to keep the following things in mind :

  1. If a class contains abstract methods, the class should be abstract.

  2. An abstract class can contain both abstract and other normal methods.

  3. A class can be abstract without any abstract methods.

  4. We can’t instantiate one abstract class.

  5. We can only extend one abstract class.

  6. If one class extends abstract class, they need to override all abstract methods. Normal methods are not required to override.

Syntax of an abstract class :

abstract keyword is used to define one abstract class. The syntax of an abstract class looks like below :

abstract class Name{

}

Example of an abstract class :

abstract class Vehicle {
  String getColor();
  String getType() {
    return 'Vehicle';
  }
}

class Car extends Vehicle {
  
  String getColor() {
    return 'Red';
  }
}

class Bus extends Vehicle {
  
  String getColor() {
    return 'Blue';
  }

  
  String getType() {
    return 'Bus';
  }
}

main() {
  var car = Car();
  var bus = Bus();

  print('Car type : ${car.getType()}, color : ${car.getColor()}');
  print('Bus type : ${bus.getType()}, color : ${bus.getColor()}');
}

Explanation :

  • Vehicle is an abstract class with one abstract method getColor() and one normal method getType().
  • Car and Bus are two classes that extend Vehicle.
  • getColor is an abstract method. So, we need to override it in both of these classes.
  • getType is not an abstract method. It is not required to override. We are overriding it in Bus class but not in Car class.

Output :

It will print the below output :

Car type : Vehicle, color : Red
Bus type : Bus, color : Blue

Similar tutorials :