scala java抽象理解_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,混入了Incrementing和Doubling,它的行为就会是先跑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 buf;

private ArrayBuffer 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)new ArrayBuffer();

}

}

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

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这个静态方法,把自己和数字都传入

Doubling$class.put则会先把数字乘以二,然后把乘积传给MagicQueue的chap12$Doubling$$super$put

MagicQueue的chap12$Doubling$$super$put方法则会把MagicQueue自己的实例以及乘积都传给Incrementing$class.put这个静态方法

Incrementing$class.put则会把接收到的参数,也就是乘积,加一,然后把加和后的数字传给MagicQueue的chap12$Incrementing$$super$put

MagicQueue的chap12$Incrementing$$super$put最终把乘以二又加了一的数字传给了super.put

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值