
Abstract Classes in Dart
30 March, 2023
1
1
0
Contributors
Abstract Classes
Abstract classes are classes in the Dart programming language that cannot be instantiated on their own, and are used as a base class for other classes. They are used to define a common interface or set of behavior for a group of related classes, and allow a programmer to define methods that any concrete subclass must implement.
Syntax
The syntax for defining an abstract class in Dart is as follows:
abstract class ClassName {
// class members (fields, methods, etc.)
}
An abstract class can have both abstract and concrete methods. Abstract methods are methods without a body that must be implemented by any concrete subclass. Concrete methods are regular methods with a body that can be used by the abstract class or its subclasses.
Here is an example of an abstract class in Dart:
abstract class Shape {
double get area; // abstract method
void draw() { // concrete method
print("Drawing a shape...");
}
}
This abstract class defines an abstract method called area
and a concrete method called draw
.
Subclassing an abstract class
To subclass an abstract class, you can use the extends
keyword followed by the name of the abstract class. The subclass must implement any abstract methods defined in the abstract class, using the @override
annotation.
Here is an example of a concrete subclass of the Shape
abstract class:
class Rectangle extends Shape {
double width;
double height;
Rectangle(this.width, this.height);
@override
double get area => width * height; // implementing the abstract method
@override
void draw() {
print("Drawing a rectangle...");
}
}
This subclass defines a Rectangle
object with two fields: width
and height
. It also implements the abstract methods area
and draw
defined in the Shape
abstract class.
Using an abstract class
Since abstract classes cannot be instantiated on their own, you must use a concrete subclass to create an object. You can then use the object to access the concrete methods defined in the abstract class or its subclasses.
Here is an example of using the Rectangle
subclass:
Rectangle myRectangle = Rectangle(10, 20);
myRectangle.draw(); // prints "Drawing a rectangle..."
print(myRectangle.area); // prints 200
Conclusion
Abstract classes are an important concept in the Dart programming language. They allow a programmer to define a common interface or set of behavior for a group of related classes, and require any concrete subclass to implement certain methods. They are a useful tool for organizing and structuring code, and help ensure that certain methods are implemented in a consistent way across multiple classes.