Abstract Class in Dart
Abstract Class
Abstraction is the class that contains one or more abstract methods (methods without implementation). It has basic syntax needed for the class but are not complete. Hence, it declared abstract. You can declare class abstracts using the keyword abstract
in dart.
Note: Abstract class may or may not contain abstract methods, but a class having at least one abstract method must declare abstract.
Key Features
- Abstract class cannot be initialized.
- It can have both abstract and non-abstract methods.
- It is declared with abstract keyword.
- It can be inherited using the extends keyword then the abstract methods need to be implemented.
Syntax
abstract class ClassName {
//Body of abstract class
method1();
method2();
}
Example
abstract class Vehicle {
printVehicleName();
printSupplierName() {
print('Supplier: TATA Motors');
}
}
class Truck extends Vehicle {
@override
printVehicleName() {
print("This is a truck.");
}
}
void main(List<String> args) {
var truck = Truck();
truck.printVehicleName();
truck.printSupplierName();
}
In the above example, the Vehicle class is created and marked as an abstract class which contains the abstract method printVehicleName()
and the non-abstract method printSupplierName()
. Class Turck extends the class Vehicle and then implements the class Vehicle. In the main method, object of the truck is created which then calls the printVechicleName()
and printSupplierName()
from the parent class.