Home > Blockchain >  Dart implements/extends for abstract class
Dart implements/extends for abstract class

Time:01-24

For abstract classes is there difference between implements and extends? Which one should I use? In Java for interfaces you would use implements, but I see dart doesn't have interfaces and both implements/extends work. If I want to declare abstract class for my api methods, should I use implements or extends?

void main() {
  User user = new User();
  user.printName();
}

abstract class Profile {
  String printName();
}

class User extends Profile {
  @override
  String printName() {
    print("I work!!");
    return "Test";
  }
}

CodePudding user response:

All classes in Dart can be used as interfaces. A class being abstract means you cannot make an instance of the class since some of its members might not be implemented.

extends means you take whatever a class already have of code and you are then building a class on top of this. So if you don't override a method, you get the method from the class you extends from. You can only extend from one class.

implements means you want to just take the interface of class but come with your own implementation of all members. So your class ends up being compatible with another class but does not come with any of the other class's implementation. You can implement multiple classes.

A third options, which you did not mention, is mixin which allow us to take the implementation of multiple mixin defined classes and put them into our own class. You can read more about them here: https://dart.dev/guides/language/language-tour#adding-features-to-a-class-mixins

  •  Tags:  
  • Related