编程语言
首页 > 编程语言> > java – Dart中的抽象基类

java – Dart中的抽象基类

作者:互联网

我已经用Java编程了将近两年,但我现在更多地转向Web编程,因此转向Javascript,或者我的情况转向Dart.对于我正在研究的项目,我希望有抽象基类,就像我在Java中一样.我一直在网上看,但我在Dart的抽象课上找不到任何东西.我只找到了this article from the dartlang site on mixins,在一个例子中,它使用了一个类的abstract关键字.但我真的不了解mixins原理.

有人可以将这个简单的Java抽象基类示例转换为Dart,以便我可以基本了解如何在Dart中完成它吗?该示例涵盖抽象基类(当然,使用抽象方法),多态,转换对象,方法重载(在本例中是构造函数),调用超级构造函数并调用重载自己的构造函数.

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

这个简单的实现怎么样?

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

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

// Calling abstract method
car.accelerate();

解决方法:

实际上它在飞镖中变得更简单(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();
}

标签:java,oop,dart,abstract-class,base-class
来源: https://codeday.me/bug/20190712/1441517.html