Sobes.tech
Junior

What is an abstract class?

sobes.tech AI

Answer from AI

An abstract class is a class that cannot be instantiated directly using the new operator. It serves as a base for other classes and can contain abstract methods (without implementation) and regular methods (with implementation). Abstract classes are defined with the abstract keyword.

Key features:

  • Cannot be instantiated: It is impossible to create an object of the abstract class itself.
  • Can contain abstract methods: Methods without a body that must be overridden in derived classes.
  • Can contain regular methods: Methods with implementation that can be inherited or overridden.
  • Inheritance: Derived classes inherit from the abstract class and are required to implement all its abstract methods.

Example:

abstract class Shape {
  // Abstract method without implementation
  double getArea();

  // Regular method with implementation
  void describe() {
    print('This is a shape.');
  }
}

class Circle extends Shape {
  double radius;

  Circle(this.radius);

  // Implementation of the abstract method
  @override
  double getArea() {
    return 3.14 * radius * radius;
  }
}

class Square extends Shape {
  double side;

  Square(this.side);

  // Implementation of the abstract method
  @override
  double getArea() {
    return side * side;
  }
}