Sobes.tech
Junior — Middle

Is it possible to override methods or properties in Dart language?

sobes.tech AI

Answer from AI

Yes, in Dart language, you can override methods and properties in subclasses.

To do this, you need to declare a method or getter/setter with the same name as in the base class in the subclass. It is recommended to use the @override annotation to explicitly indicate the override.

Example:

class Animal {
  void speak() {
    print('Animal sound');
  }

  String get name => 'Animal';
}

class Dog extends Animal {
  @override
  void speak() {
    print('Bark');
  }

  @override
  String get name => 'Dog';
}

void main() {
  var dog = Dog();
  dog.speak(); // Outputs: Bark
  print(dog.name); // Outputs: Dog
}

Thus, Dart supports overriding methods and properties to implement polymorphism.

Is it possible to override methods or properties in… - sobes.tech