【Scala面向对象】33、特质Trait

在这里插入图片描述

Scala 不支持传统意义上的多继承,一个类不能直接继承多个父类。Scala 使用 Trait 来解决多重继承的问题,Trait 类似于接口和混入(mixin)。

在 Scala 中,一个类可以继承一个父类,并可以同时混入多个 Trait。这样,一个类可以获得多个 Trait 中定义的方法和字段,从而达到类似多重继承的效果。

一、定义语法

在 Scala 中,定义 Trait 使用关键字 trait,其语法如下:

trait TraitName {
   
    
    
  // Trait 的成员(方法和字段)声明
  def method1(

猜你喜欢

转载自blog.csdn.net/m0_47256162/article/details/132160280