Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dart
extends
communitycreator

What is the extends keyword in Dart?

Maria Elijah

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

dart
extends
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring