scala 抽象类(abstract)与特质(trait)

抽象类

In Scala, an abstract class is constructed using the abstract keyword. It contains both abstract and non-abstract methods and cannot support multiple inheritances.

在scala中,抽象类带abstract关键字,内部既可以包含抽象方法,又可以写非抽象的方法,抽象类不支持多继承,而且不能创建抽象类的实例。

  // Scala program to illustrate how to 
// create an abstract class 

// Abstract class 
abstract class Abstclass 
{ 
    
    // Abstract and non-abstract method 
    def portal 
    def tutorial() 
    { 
        println("Scala tutorial") 
    } 

} 

// GFG class extends abstract class 
class GFG extends Abstclass 
{ 
    def portal() 
    { 
        println("Welcome!! GeeksforGeeks") 
    } 
} 

object Main 
{ 
    
    // Main method 
    def main(args: Array[String]) 
    { 
        // object of GFG class 
        var obj = new GFG (); 
        obj.tutorial() 
        obj.portal() 
    } 
} 
// Output :
// Scala tutorial
// Welcome!! GeeksforGeeks

特质(Traits)

Like a class, Traits can have methods(both abstract and non-abstract), and fields as its members. Traits are just like interfaces in Java. But they are more powerful than the interface in Java because in the traits we are allowed to implement the members.
特质是一些字段和行为的集合,可以有抽象方法、非抽象方法和字段,类似于Java中的接口(interface),但是比接口更加强大,因为特质可以实现成员函数或属性,并且通过with关键字,一个类可以扩展多个特质。

 // Scala program to illustrate how to  
// create traits 
  
// traits 
trait mytrait 
{ 
      
    // Abstract and non-abstract method 
    def portal 
    def tutorial() 
    {  
        println("Scala tutorial") 
    } 
  
} 
  
// GFG class extends trait 
class GFG extends mytrait 
{ 
    def portal() 
    { 
        println("Welcome!! GeeksforGeeks") 
    } 
} 
  
object Main  
{ 
      
    // Main method 
    def main(args: Array[String])  
    { 
          
        // object of GFG class 
        var obj = new GFG (); 
        obj.tutorial() 
        obj.portal() 
    } 
} 
// Output:
// Scala tutorial
// Welcome!! GeeksforGeeks

二者区别

那么什么时候应该使用特质而不是抽象类呢?如果你想定义一个类似接口类型,你可能会在特质和抽象类之间难以取舍。这两种形式都可以让你定义一个类型的一些行为,并要求继承者定义一些其他行为。

traits abstract class 说明
Traits support multiple inheritance. Abstract class does not support multiple inheritance. trait支持多继承,抽象类不行
We are allowed to add a trait to an object instance. We are not allowed to add an abstract class to an object instance. 可以将Trait赋给对象实例,抽象类不行
Traits does not contain constructor parameters. Abstract class contain constructor parameters. trait不能定义构造参数,抽象类可以
Traits are completely interoperable only when they do not contain any implementation code. Abstract class are completely interoperable with Java code. trait只有在不包含任何实现代码时才完全可互操作,抽象类完全可以与Java代码互操作(因为trait在不包含任何实例代码的时候会被编译器解析成java的interface)
Traits are stackable. So, super calls are dynamically bound. Abstract class is not stackable. So, super calls are statically bound. trait是可堆叠的,父类调用可动态绑定在一起(编译器的工作),java不可堆叠,父类调用是静态绑定

上面是特质和抽象类的主要区别,其中有几个特质的特征比较特殊,比如trait可堆叠,trait可赋给对象实例,下面详细介绍一下特质的这两个特征。

Stackable Traits

Stackable traits是一种怎样的特性呢?

来举一个🌰

abstract class IntQueue {
  def get(): Int
  def put(x: Int)
}

定义一个IntQueue,抽象类,定义了get和put,没有实现。

class BasicIntQueue extends IntQueue {
  private val buf = new ArrayBuffer[Int]

  def get() = buf.remove(0)

  def put(x: Int) = {
    buf += x
  }
}

再定义一个BasicIntQueue````,把上述IntQueue```实现了。 它的实现没有什么花样,就是先进先出。

接下来就有意思了:

trait Incrementing extends IntQueue {
  abstract override def put(x: Int) = {
    super.put(x + 1)
  }
}

trait Doubling extends IntQueue {
  abstract override def put(x: Int) = {
    super.put(2 * x)
  }
}

定义了两个trait,都扩展自IntQueue。 一个是把数字先加一再放进队列,另一个是先把数字加倍再放入队列。

要注意这里的modifier:abstract override,以及在trait中对super的调用。稍后反编译的时候可以看懂它们的真实含义。

那这两个trait可以怎么使用呢?

class MagicQueue extends BasicIntQueue with Incrementing with Doubling

定义一个MagicQueue,它扩展自BasicIntQueue,同时mix in了上面的两个trait。

MagicQueue它自己是一行实现代码都没有的,那么它的行为会是什么样子呢?

val queue = new MagicQueue

queue.put(100)
queue.get() //会返回201

queue.put(500)
queue.get() //会返回1001

可以看到,它会先把数字乘以二,然后加一再放入队列。

MagicQueue继承了BasicIntQueue,混入了IncrementingDoubling,它的行为就会是先跑Doubling后跑Incrementing最后跑BasicIntQueue从右到左依序生效)。

这是种很实用的语言特性,你可以写很多个不同的trait,让它们都extend IntQueue。 同时写很多class让它们实现IntQueue。 然后每一个实现了IntQueue的class都可以和任意一个或者任意多个trait随意组合应用。

这给语言的使用者提供了很强的composition的便利性。

那下面反编译一下jar包看下这个语言特性是如何实现的。

public abstract class IntQueue
{
    public abstract int get();

    public abstract void put(final int p0);
}

public class BasicIntQueue extends IntQueue
{
    private final ArrayBuffer<Object> buf;

    private ArrayBuffer<Object> buf() {
        return this.buf;
    }

    public int get() {
        return BoxesRunTime.unboxToInt(this.buf().remove(0));
    }

    public void put(final int x) {
        this.buf().$plus$eq((Object)BoxesRunTime.boxToInteger(x));
    }

    public BasicIntQueue() {
        this.buf = (ArrayBuffer<Object>)new ArrayBuffer();
    }
}

首先,IntQueueBasicIntQueue反编译之后平淡无奇,一个抽象类,一个实现类。

public interface Doubling
{
    void chap12$Doubling$$super$put(final int p0);

    void put(final int p0);
}

public abstract class Doubling$class
{
    public static void put(final Doubling $this, final int x) {
        $this.chap12$Doubling$$super$put(2 * x);
    }

    public static void $init$(final Doubling $this) {
    }
}

Doubling这个trait则被编译成了一个接口加一个抽象类,其中除了put之外还有一个名字有点奇怪的方法声明。 稍后可以看到它有什么用。

public interface Incrementing
{
    void chap12$Incrementing$$super$put(final int p0);

    void put(final int p0);
}

public abstract class Incrementing$class
{
    public static void put(final Incrementing $this, final int x) {
        $this.chap12$Incrementing$$super$put(x + 1);
    }

    public static void $init$(final Incrementing $this) {
    }
}

Incrementing则和Doubling是一个路数。

(这里出现的chap12字样是代码中package的名字)

最后揭露真相的时候到了:

public class MagicQueue extends BasicIntQueue implements Incrementing, Doubling
{
    public void chap12$Doubling$$super$put(final int x) {
        Incrementing$class.put((Incrementing)this, x);
    }

    public void put(final int x) {
        Doubling$class.put((Doubling)this, x);
    }

    public void chap12$Incrementing$$super$put(final int x) {
        super.put(x);
    }

    public MagicQueue() {
        Incrementing$class.$init$((Incrementing)this);
        Doubling$class.$init$((Doubling)this);
    }
}

MagicQueue本身被编译成了以上的样子。

我们看一下它的put方法被调用时会怎样呢?

1.它去调用Doubling$class.put这个静态方法,把自己和数字都传入

  1. Doubling$class.put则会先把数字乘以二,然后把乘积传给MagicQueuechap12$Doubling$$super$put
  2. MagicQueuechap12$Doubling$$super$put方法则会把MagicQueue自己的实例以及乘积都传给Incrementing$class.put这个静态方法
  3. Incrementing$class.put则会把接收到的参数,也就是乘积,加一,然后把加和后的数字传给MagicQueuechap12$Incrementing$$super$put
  4. MagicQueuechap12$Incrementing$$super$put最终把乘以二又加了一的数字传给了super.put
  5. super.put其实就是BasicIntQueue.put了,到这里终于把数字存到ArrayBuffer里面了

这样,Doubling, Incrementing, BasicIntQueue它们三个的行为就堆叠(stackable)在一起了。

Adding a Trait to an Object Instance

下面就是在创建对象的时候mix in特质的例子:


trait Angry {
  println("You won't like me ...")
}

class Test

object Test extends App {
  val hulk = new Test with Angry
}

// Output:
// You won't like me ...

在特质中构造函数执行println操作,所以执行new Test对象的时候会执行println。该特性应用场景比如可以写一个打印日志的trait,方便调试代码:

trait Debugger {
  def log(message: String) {
    // do something with message
  }
}

// no debugger
val child = new Child

// debugger added as the object is created
val problemChild = new ProblemChild with Debugger

参考:
https://www.geeksforgeeks.org/difference-between-traits-and-abstract-classes-in-scala/
https://cuipengfei.me/blog/2017/06/14/desugar-scala-stackable-traits/
https://www.oreilly.com/library/view/scala-cookbook/9781449340292/ch08s09.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,064评论 5 466
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,606评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,011评论 0 328
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,550评论 1 269
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,465评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,919评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,428评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,075评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,208评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,185评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,191评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,914评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,482评论 3 302
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,585评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,825评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,194评论 2 344
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,703评论 2 339

推荐阅读更多精彩内容