Search code examples
inheritancedartsuperclass

About super-class and inheritance


void main() {
  Car myNormalCar = Car(20);

  print(myNormalCar.numberOfSeat);

  myNormalCar.drive('academia');
}

class Car {
  int numberOfSeat = 40;
  int height = 30;

  Car(int seat) {
    numberOfSeat = seat;
  }

  void drive(String name) {
    print('the wheels turn:$name');
  }
}

class ElectricCar extends Car {}

ElectricCar here shows that "The superclass 'Car' doesn't have a zero argument constructor". I want to assign different values for properties that has been inherited from Car for Electric Car.How can I do that?


Solution

  • You need to call the constructor of Car inside ElectricCar since you are extending from Car. I am not sure what you actually want but you can e.g. do the following if you want to add more properties to ElectricCar but still want to be able to set numberOfSeat:

    class ElectricCar extends Car {
      int power;
    
      ElectricCar(this.power, int seat) : super(seat);
    }
    

    The important part is you need to call the constructor of Car with the constructor of ElectricCar since the constructor of Car is the code which know how to initialize the Car part of ElectricCar.