/** * Created by Jxy on 2018/12/21 14:07 * trait关键字 * 声明trait中的方法和任何常规方法一样 * trait声明抽象方法需要在实现类中实现 * 也可以有私有方法 Those methods will not appear in the trait contract interface * groovy接口 * trait也可以实现接口 */ /* 普通方法 */ trait FlyingAbility { String fly() { "I'm flying!" } } class Bird implements FlyingAbility {} def b = new Bird() assert b.fly() == "I'm flying!" println(b.fly()) /* 抽象方法 */ trait Greetable { abstract def name() def getName(){ "hello , ${name()}" } } class GreetableImpl implements Greetable{ @Override def name() { "jser" } } def p = new GreetableImpl() println(p.getName()) /* 接口 */ interface Named { String name() } trait Greetable1 implements Named { String greeting() { "Hello, ${name()}!" } } class Person1 implements Greetable1 { String name() { 'Bob' } } def p1 = new Person1() assert p1.greeting() == 'Hello, Bob!' assert p1 instanceof Named assert p1 instanceof Greetable1 /* 公共字段 避免钻石问题 */ trait Named1 { public String name } class Person2 implements Named1 {} def p2 = new Person2() p2.Named1__name = 'Bob' println(p2.Named1__name)