Sun, Dec 4, 2022
Read in 2 minutes
In this post we learn about "abstract" keyword in Dart language.
In Dart, the abstract
keyword is used to define abstract classes and abstract methods. An abstract class cannot be instantiated directly; it can only be used as a base class for other classes. An abstract method is a method that does not have a body, and it must be implemented by any concrete subclass.
Here’s an example of an abstract class in Dart:
abstract class Shape {
double get area;
void draw();
}
In this example, Shape
is an abstract class that defines two abstract methods: area
and draw
. The area
method is a getter method that does not have a body, and it returns a double
. The draw
method is a void method that also does not have a body.
Any class that extends the Shape
class must implement the area
and draw
methods. Here’s an example of a concrete subclass of Shape
:
class Rectangle extends Shape {
double width, height;
Rectangle(this.width, this.height);
double get area => width * height;
void draw() {
print('Drawing a rectangle with width=$width and height=$height');
}
}
In this example, Rectangle
is a concrete subclass of Shape
that implements the area
and draw
methods. The area
method is implemented as a getter method that calculates the area of the rectangle, and the draw
method is implemented as a void method that prints a message to the console.
Note that if a class extends an abstract class but does not implement all the abstract methods, it must also be declared as abstract. Here’s an example:
abstract class Shape {
double get area;
void draw();
}
class Circle extends Shape {
double radius;
Circle(this.radius);
double get area => 3.14 * radius * radius;
// draw() method is not implemented, so Circle class is also declared as abstract
}
In this example, Circle
is a subclass of Shape
that implements the area
method but does not implement the draw
method. Since it does not implement all the abstract methods, it must also be declared as abstract.