Abstract base class in Dart
Actually it does become simpler in dart (https://dartpad.dartlang.org/37d12fa77834c1d8a172)
// Abstract base class
abstract class Vehicle {
final int maxSpeed;
int speed = 0;
Vehicle([this.maxSpeed = 0]);
void accelerate();
void brake();
}
// Subclass of Vehicle, the abstract baseclass
class Car extends Vehicle {
final int doors;
Car(int maxSpeed, this.doors) : super(maxSpeed);
@override
void accelerate() {
if (speed > maxSpeed) {
speed = maxSpeed;
return;
}
speed += 2;
}
@override
void brake() {
if (speed - 2 < 0) {
speed = 0;
return;
}
this.speed -= 2;
}
}
main() {
// Polymorphism
Vehicle car = new Car(180, 4);
// Casting
int doors = (car as Car).doors;
// Calling abstract method
car.accelerate();
}
I would take a look at the Language tour, there's a whole section on abstract classes
Key points:
- Abstract classes in Dart have to be marked as
abstract
. - An abstract class can have "abstract methods", you just have to omit the body
- A concrete class can mark itself as "implementing" the abstract class' contract with the keyword
implements
. This will force you to implement all the expected behavior on the concrete class, but it won't inherit the abstract class' provided methods' implementation. - You can extend an abstract class with the keyword
extends
, and the concrete class will inherit all possible behavior of the abstract class.
That's pretty much it!
Also, you might want to take a look at mixins, there's a section below the one I have you in the Language tour.