3

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";
  }
}

Dave
  • 1
  • 1
  • 9
  • 38
  • A complete answer is also available here : https://stackoverflow.com/questions/55295782/extends-versus-implements-versus-with – Jack' Feb 14 '23 at 18:49

2 Answers2

11

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

julemand101
  • 28,470
  • 5
  • 52
  • 48
  • would it be better to write logic of methods inside an abstract class and then only extend it, or write the method name and implement somewhere else? – Dave Jan 23 '22 at 17:10
  • 1
    Depends on your application. There are also extension methods that can be useful in some scenarios: https://dart.dev/guides/language/extension-methods . So without knowing much about your application I cannot really give any specific recommendation other than: It depends. :) – julemand101 Jan 23 '22 at 17:16
0

another definition that may help you got the point.. Use extends make class inherits (extends) his parent, where you extend(have) his properties even if you don't override parent class's properties you can use the parent class's properties, methods beside his own properties and methods, also you should validate that this class(child) commits it's parent class and doesn't break the restrictions of the parent.. you can only inherit from 1 class... where as

Use implements when you want the class just restrict to the abstract class properties but you have your own implementation for these properties... use can implements multiple interfaces using "," for concatenate among the interfaces.