I have been programming in Java for nearly two years but I am now more shifting to web programming and thus to Javascript, or in my case to Dart. For a project I'm working on I would like to have abstract base classes, just I would have in Java. I have been looking on the internet but I can't find anything on abstract classes at all for Dart. I only found this article from the dartlang site on mixins, that in an example uses the abstract keyword for a class. But I don't really understand the mixins principle.
Could somebody translate this easy Java abstract base class example to Dart so that I can have a basic understanding on how it would be done in Dart? The example covers abstract base class (ofcourse, with abstract methods), polymorphism, casting objects, method overloading (in this case it is the constructor), calling super-constructor and calling overloaded own constructor.
// Abstract base class
abstract class Vehicle {
protected final int maxSpeed;
protected int speed;
Vehicle() {
this(0);
}
Vehicle(int maxSpeed) {
this.maxSpeed = maxSpeed;
speed = 0;
}
public int getMaxSpeed() {
return maxSpeed;
}
abstract void accelerate();
abstract void brake();
}
// Subclass of Vehicle, the abstract baseclass
class Car extends Vehicle {
public final int doors;
Car(int maxSpeed, int doors) {
super(maxSpeed);
this.doors = doors;
}
@Override
void accelerate() {
if (speed>maxSpeed) {
speed = maxSpeed;
return;
}
speed += 2;
}
@Override
void brake() {
if (speed - 2 < 0) {
speed = 0;
return;
}
this.speed -= 2;
}
}
And how would this easy implementation look like?
// Polymorphism
Vehicle car = new Car(180, 4);
// Casting
int doors = ((Car)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
.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.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.