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
extendskeyword.
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
extendskeyword 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 Trianglevar triangle = Triangle();// Invoke method of class Shape// using class Triangle instancetriangle.display();// Invoke method of class Shapetriangle.message();}
Explanation
- Lines 1–5: We create a class
Shapewith a method nameddisplay(). - Lines 7–9: We create a subclass named
Triangleusing theextendskeyword. ThisTriangleclass inherits the method defined in theShapeclass. - Lines 13–21: In the
main()function, we create an instance of the classTrianglenamedtriangle. Next, we call the method inherited from classShapeusingtriangle. We also invoke the method defined in the classTriangleusingtriangle.
Note: Dart only allows us to
extendone class.