admin 管理员组

文章数量: 887021

[Learning

Trait

  • Trait
  • 疑问

Trait

Trait具有Java Interface和抽象类的双重特征。是Groovy解决多重继承需求的手段

  • 具有Java Interface的特征:
    1. 通过implements可实现多个trait。
    2. 和Java8以上的版本类似可定义方法的Default实现。
  • 具有Java 抽象类的特征
    可定义Field

例如:

import groovy.transform.*@Canonical
class Meat{double weightInKg 
}@Canonical
class Grass {double weightInKg 
}trait Carnivore{double weightAsCarnivoredef eat(Meat meat){weightAsCarnivore += meat.weightInKg * getAbsorptionRateOfMeat()}abstract double getAbsorptionRateOfMeat()
}trait Herbivores {double weightAsHerbivoresdef eat(Grass grass){weightAsHerbivores += grass.weightInKg * getAbsorptionRateOfGrass()}abstract double getAbsorptionRateOfGrass()
}@Canonical
class Pig implements Carnivore, Herbivores {double absorptionRateOfMeat = 0.8double absorptionRateOfGrass = 0.5def double getWeightInKg(){return weightAsCarnivore + weightAsHerbivores}
}def peiqi = new Pig()
def meatWeight = 100
peiqi.eat(new Meat(meatWeight))
println "After eat ${meatWeight}kg meat, weight of peiqi is ${peiqi.weightInKg}kg"
def grassWeight = 500
peiqi.eat(new Grass(grassWeight))
println "After eat ${grassWeight}kg grass, weight of peiqi is ${peiqi.weightInKg}kg"

执行结果如下:

After eat 100kg meat, weight of peiqi is 80.0kg
After eat 500kg grass, weight of peiqi is 330.0kg

疑问

  • 问:当 不同 的Trait定义了 相同 的field或者method时, 将它们同时implements的时候,会发生什么?

    现象: 处于implements语句之后的Trait所定义的Field和method会覆盖之前的Trait。例如:trait Atrait B 都定义有 int weight, 当 class C implements A, B 时,B中的weight 会覆盖A。

本文标签: learning