Start Coding

Topics

Abstract Classes in Dart

Abstract classes are a fundamental concept in Dart's object-oriented programming model. They serve as blueprints for other classes, defining a common interface without providing complete implementations.

What are Abstract Classes?

An abstract class is a class that cannot be instantiated directly. It's designed to be subclassed, providing a common structure for related classes. Abstract classes can contain both abstract and concrete methods.

Syntax and Usage

To define an abstract class in Dart, use the abstract keyword before the class declaration:

abstract class Shape {
  double area();  // Abstract method
  void display() {
    print('This is a shape.');  // Concrete method
  }
}

Key Features

  • Abstract classes can't be instantiated directly
  • They can contain abstract methods (without implementation) and concrete methods (with implementation)
  • Subclasses must implement all abstract methods
  • They can have constructors, fields, and getters/setters

Practical Example

Let's create a more comprehensive example to illustrate the use of abstract classes:

abstract class Animal {
  String name;
  
  Animal(this.name);
  
  void makeSound();  // Abstract method
  
  void introduce() {
    print('I am a $name.');
  }
}

class Dog extends Animal {
  Dog(String name) : super(name);
  
  @override
  void makeSound() {
    print('Woof!');
  }
}

class Cat extends Animal {
  Cat(String name) : super(name);
  
  @override
  void makeSound() {
    print('Meow!');
  }
}

void main() {
  var dog = Dog('Buddy');
  var cat = Cat('Whiskers');
  
  dog.introduce();
  dog.makeSound();
  
  cat.introduce();
  cat.makeSound();
}

In this example, Animal is an abstract class with both an abstract method (makeSound()) and a concrete method (introduce()). The Dog and Cat classes extend Animal and provide implementations for the abstract method.

Best Practices

  • Use abstract classes to define a common interface for a group of related classes
  • Implement abstract classes when you want to ensure certain methods are present in child classes
  • Consider using abstract classes for base classes in your class hierarchy
  • Combine abstract classes with Dart Interfaces for more flexible designs

Related Concepts

To deepen your understanding of Dart's object-oriented features, explore these related topics:

Abstract classes are a powerful tool in Dart for creating flexible and maintainable code structures. They provide a way to define common behaviors and enforce implementation in subclasses, promoting code reuse and consistency in your Dart projects.