Home > Blockchain >  Extending class in Dart
Extending class in Dart

Time:03-18

So I have this class CarPrice, I want to create new Car with a price with it and I want to display all the data about it, however I have no clue how do I access the object in my toString method. In my toString method it says null null. How can I actually display the name and price of the new created object?

class Car {
  String? name;
  Car(String name) {
     name = name;
  }
}

class CarPrice extends Car {
  String? price;
  
  CarPrice(String price, String name) : super(name) {
    price = price;
  }
  
  String toString() {
    return '$name $price';
  }
}

void main() {
  CarPrice test = new CarPrice("1000", "test");
  print(test.toString());
}

CodePudding user response:

You left the this reference out from your constructors. Your code should look like something like this:

class Car {
  String name;
  Car(String name) {
    this.name = name;
  }
}

class CarPrice extends Car {
  String price;
  
  CarPrice(String price, String name) : super(name) {
    this.price = price;
  }
  
  String toString() {
    return '$name $price';
  }
}

void main() {
  CarPrice test = new CarPrice("1000", "test");
  print(test.toString());
}

And it gives the following result:
test 1000

  •  Tags:  
  • dart
  • Related