0

I have a pretty basic question.

abstract class Vehicle{
int mileage;

Vehicle(this.mileage);
}

class Truck extends Vehicle{
String plateNumber;
@override
String mileage;

Truck(this.plateNumber, this.mileage);
}

How I can override the mileage field from the Vehicle class properly? I want to change the type of field in my Truck class

Gwhyyy
  • 7,554
  • 3
  • 8
  • 35
  • 1
    Overriding a member with a completely different type does not make sense. [Derived classes should be *substitutable* for a base class](https://stackoverflow.com/questions/56860/). If you pass a `Truck` instance where a `Vehicle` is expected, and the receiver attempts to assign an `int` to `mileage`, what do you expect should happen? – jamesdlin Apr 01 '22 at 07:58
  • Thanks for answer. I understand that passing different type than expected would throw an error. Maybe I should better explain what I would like to achieve. I have two classes similar to Truck and Vehicle, I would like to have access in Truck class to fields from Vehicle to display them for the user. However, some of the fields are already defined in Truck class with different type. How I should approach this? – Julian Modlinski Apr 01 '22 at 08:08
  • If `Truck` is not substitutable for `Vehicle`, then `Truck` should not inherit from `Vehicle`. Perhaps you should use composition instead, and/or maybe the fields should not have colliding names. It's hard to answer from your vague description and contrived example. – jamesdlin Apr 01 '22 at 09:57
  • Sorry, I think I just created unnecessary confusion – Julian Modlinski Apr 01 '22 at 11:07

0 Answers0