Comparison and application scenarios of traits and abstract classes

Same point

  • Both can contain abstract methods, abstract properties and non-abstract methods and non-abstract properties.
  • Neither can be instantiated. But there are default construction methods.

difference

  • The construction methods of abstract classes can pass parameters, but the construction methods of traits cannot pass parameters.

Application scenarios

  • Prioritize the selection of traits. Scala is single inheritance. If it is directly inherited, it is not convenient for subsequent extensions.
  • A class abstracts the commonality of a large number of objects, and an abstract class abstracts the commonality of a large number of classes. Generally, subclasses and superclasses must satisfy the rule of "subclass is a superclass".
  • Traits generally abstract behaviors and define norms.

Guess you like

Origin blog.csdn.net/FlatTiger/article/details/114536227