Sobes.tech
Junior

What is the difference between the keywords Abstract and late in Dart?

sobes.tech AI

Answer from AI

Abstract is used to create abstract classes that cannot be instantiated directly. An abstract class can contain both implemented and abstract (without implementation) methods. Abstract methods must be implemented in non-abstract subclasses.

late is used for deferred initialization of variables. A variable marked as late is guaranteed to be initialized before its first use. If a variable is declared as late and not initialized before its first access, a runtime error will occur. This is useful for initializing variables whose values depend on other variables or logic executed after declaration.

Property Abstract late
Applied to Classes Variables
Purpose Defines a contract, template Deferred initialization
Instantiation Cannot be done directly Possible
Mandatory Implementation of methods in subclasses (for abstract methods) Initialization before first use

Example of abstract:

// Defining an abstract class
abstract class Shape {
  // Abstract method
  double getArea();

  // Implemented method
  void printName() {
    print("This is a shape");
  }
}

// Implementation of the abstract class
class Circle extends Shape {
  double radius;

  Circle(this.radius);

  @override
  double getArea() {
    return 3.14 * radius * radius;
  }
}

// Cannot create an instance of Shape:
// var shape = Shape(); // Error

Example of late:

// Declaration of a variable with deferred initialization
late String name;

void setupName() {
  // Initialize the variable before first use
  name = "Flutter Developer";
}

void greet() {
  // First use of the variable name after initialization
  print("Hello, $name!");
}

void main() {
  setupName();
  greet(); // Will print "Hello, Flutter Developer!"

  // If greet() was called before setupName(), a runtime error would occur
  // greet(); // Error if name was not initialized
}