Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

dart - "extends" versus "implements" versus "with"

I want to understand the difference between extends, implements and with. When do I use each keyword?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Extends:

Use extends to create a subclass, and super to refer to the superclass.

Extends is the typical OOP class inheritance. If class a extends class b all properties, variables, functions implemented in class b are also available in class a. Additionally you can override functions etc.

You use extend if you want to create a more specific version of a class. For example the class car could extend the class vehicle. In Dart a class can only extend one class.


Implements:

Every class implicitly defines an interface containing all the instance members of the class and of any interfaces it implements. If you want to create a class A that supports class B’s API without inheriting B’s implementation, class A should implement the B interface.

Implements can be used if you want to create your own implementation of another class or interface. When class a implements class b. All functions defined in class b must be implemented.

When you're implementing another class, you do not inherit code from the class. You only inherit the type. In Dart you can use the implements keyword with multiple classes or interfaces.


With (Mixins):

Mixins are a way of reusing a class’s code in multiple class hierarchies.

With is used to include Mixins. A mixin is a different type of structure, which can only be used with the keyword with.

They are used in Flutter to include common code snippets. A common used Mixin is the SingleTickerProviderStateMixin.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...