Java – abstract base class in dart

I've been programming in Java for nearly two years, but now I'm turning more to web programming, so I'm turning to JavaScript, or my situation is turning to dart For the project I'm working on, I want to have abstract base classes, just as I do in Java I've been reading it online, but I can't find anything in DART's abstract class I only found this article from the dartlang site on mixins. In one example, it used the abstract keyword of a class But I really don't understand the mixins principle

Can someone convert this simple java abstract base class example to dart so that I can basically understand how to do it in dart? This example covers abstract base classes (of course, using abstract methods), polymorphism, conversion objects, method overloading (constructor in this case), calling super constructors and calling overloaded constructors

// 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;
    }
}

How about this simple implementation?

// Polymorphism
Vehicle car = new Car(180,4);

// Casting
int doors = ((Car)car).doors;

// Calling abstract method
car.accelerate();

Solution

In fact, it becomes simpler in darts( 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();
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>