What is the extends keyword in Dart?

Dart extends keyword

The extends keyword is commonly used in Dart to change the functionality of a class using inheritance.

Inheritance refers to a class’s ability to derive properties and attributes from another class. A class that inherits from another class is known as the subclass or derived class. The class whose properties and attributes are inherited is known as the parent class or superclass.

To make a subclass, we use the extends keyword.

All properties, variables, and methods implemented in a superclass are also available in a subclass if it extends the superclass. We can also override the methods of a superclass in a subclass.

Syntax

class Class_name {
//TODO: some codes
}
class newClass_name extends Class_name {
//TODO: some codes
}

Note: We can also use the extends keyword with an abstract class.

Code

The following code shows how to use the extends keyword in Dart.

class Shape {
void display() {
print('Method in Shape class');
}
}
class Triangle extends Shape {
void message(){
print('Method in Triangle class');
}
}
void main() {
// Instance of Class Triangle
var triangle = Triangle();
// Invoke method of class Shape
// using class Triangle instance
triangle.display();
// Invoke method of class Shape
triangle.message();
}

Explanation

  • Lines 1–5: We create a class Shape with a method named display().
  • Lines 7–9: We create a subclass named Triangle using the extends keyword. This Triangle class inherits the method defined in the Shape class.
  • Lines 13–21: In the main() function, we create an instance of the class Triangle named triangle. Next, we call the method inherited from class Shape using triangle. We also invoke the method defined in the class Triangle using triangle.

Note: Dart only allows us to extend one class.

Free Resources